Home > database >  Django unit test to see if model is registered to admin page
Django unit test to see if model is registered to admin page

Time:03-31

I have a URL (/admin/) that goes to my Django admin panel (my URL router:url(r'^admin/', admin.site.urls),)

This admin panel includes an admin for the Post model.

That Post model is being registered by a ModelAdmin class called PostAdmin.

admin.py:

from .models import Post

class PostAdmin(admin.ModelAdmin):

    list_display = (
        'id',
        'slug',
        'title',
        'author'
    )

admin.site.register(Post, PostAdmin)

Now I want to write a unit test for this admin.py file and I want to check that if you go to the /admin/ URL you see the Post Model.

How would you do this? I think it would be something like:

response = method_gets_url_content(`/admin/`)
assert.response.contains('Post') == True

But I'm not sure how to write a test like this since there is no method to get that URL (/admin).

CodePudding user response:

One can work with Django's test client [Django-doc]:

from django.test import TestCase
from django.contrib.auth import get_user_model

class MyTests(TestCase):
    
    @classmethod
    def setUpTestData(cls):
        self.user = get_user_model().objects.create_user(
            username='foo',
            password='bar'
        )

    def test1(self):
        self.client.force_login(self.user)
        response = self.client.get('/admin/')
        self.assertContains(response, 'Tags')
  • Related