How to test admin change views?

Question:

I got a rather complex admin change view for my Django model.

There is a lot of resources about how to test the admin list views (e.g. here), but not for the change view.

How can I create a test cases for it?

Asked By: Erik Kalkoken

||

Answers:

You can test the admin change view of any model with Django’s test client.

For that you will need the specific view URL for your model, which can be generated as described in the docs.

Here is an example how to run a simple “loads normally” test for the Group model:

from django.contrib.auth.models import User, Group
from django.test import TestCase, Client
from django.urls import reverse


def get_admin_change_view_url(obj: object) -> str:
    return reverse(
        'admin:{}_{}_change'.format(
            obj._meta.app_label,
            type(obj).__name__.lower()
        ),
        args=(obj.pk,)
    )


class TestGroupAdmin(TestCase):

    def test_change_view_loads_normally(self):
        # prepare client
        User.objects.create_superuser(
            username='superuser', password='secret', email='[email protected]'
        )
        c = Client()
        c.login(username='superuser', password='secret')                

        # create test data
        my_group = Group.objects.create(name='Test Group')

        # run test
        response = c.get(get_admin_change_view_url(my_group))
        self.assertEqual(response.status_code, 200)

Answered By: Erik Kalkoken

Here’s a version that’s more flexible to other models based off of Erik’s answer.

from django.contrib.auth.models import User, Group
from django.test import TestCase, Client
from django.urls import reverse


def get_admin_change_view_url(obj: object) -> str:
    return reverse(
        'admin:{}_{}_change'.format(
            obj._meta.app_label,
            type(obj).__name__.lower()
        ),
        args=(obj.pk,)
    )


class BaseAdminTestCaseMixin:
    def setUp(self):
        self.client = Client()
        user = User.objects.create_superuser(
            username='superuser', password='secret', email='[email protected]'
        )
        self.c.force_login(user)

    def get_instance(self):
        raises NotImplementedError()
        instance, _ = Group.objects.get_or_create(name='Test Group')
        return instance

    def test_change_view_loads_normally(self):
        instance = self.get_instance()
        response = self.client.get(get_admin_change_view_url(instance))
        self.assertEqual(response.status_code, 200)


class TestGroupAdmin(BaseAdminTestCaseMixin, TestCase):
    def get_instance(self):
        instance, _ = Group.objects.get_or_create(name='Test Group')
        return instance
Answered By: schillingt
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.