[Django]-How to test admin change views?

5đź‘Ť

âś…

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='admin@example.com'
        )
        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)

👤Erik Kalkoken

1đź‘Ť

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='admin@example.com'
        )
        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
👤schillingt

Leave a comment