Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django unit test to see if model is registered to admin page

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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).

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading