[Fixed]-Coverage test django admin custom functions

0👍

Actually i found it, and it was quite simple if someone ever need it :

def test_first_name_admin(self):
    rsf = ResponsibleStateFlow.objects.get(id = 1)
    ResponsibleStateFlowAdmin.User_Name(self, rsf)
    ResponsibleStateFlowAdmin.User_Last_Name(self, rsf)

1👍

You will have to use django client and open list page for Responsible model in django admin.

https://docs.djangoproject.com/en/1.10/topics/testing/tools/#overview-and-a-quick-example

By opening admin list page your custom functions will be called and hence will covered under tests.

So basically something like below needs to be done:

from django.test import Client, TestCase

class BaseTestCase(TestCase):
    """Base TestCase with utilites to create user and login client."""

    def setUp(self):
        """Class setup."""
        self.client = Client()
        self.index_url = '/'
        self.login()

    def create_user(self):
        """Create user and returns username, password tuple."""
        username, password = 'admin', 'test'
        user = User.objects.get_or_create(
            username=username,
            email='admin@test.com',
            is_superuser=True
        )[0]
        user.set_password(password)
        user.save()
        self.user = user
        return (username, password)

    def login(self):
        """Log in client session."""
        username, password = self.create_user()
        self.client.login(username=username, password=password)


class AdminTestCase(BaseTestCase):

    def test_responsible_list(self):
        response = self.client.get('/admin/responsilbe_list/')
        # assertions....

0👍

Complete, fast and easy:

from [your-app].admin.py import Responsible  # better name it ResponsibleAdmin

class AdminTestCase(TestCase):

fixtures = ["initial_data.json"]


def test_first_name(self):
    r = Responsible.objects.get(id = 1)
    admin_function_result = Responsible.User_Name(Responsible, obj=r)
    self.assertEquals(admin_function_result, r.user.first_name)  # alternatively, pass first_name as string 

No need to use admin logins.
Test plain functions as plain functions.

👤Alex V

0👍

The custom function needs an object derived from the queryset of the view. This should work.

from django.contrib import admin

from myapp.admin import ResponsibleAdmin  # renamed to distinguish from model class

class AdminTestCase(TestCase):

    fixtures = ["initial_data.json"]  # as in the question

    def test_first_name(self):
        r = Responsible.objects.get(id=1)
        r_admin = ResponsibleAdmin(Responsible, admin.site)
        obj = r_admin.get_object(None, r.id)
        admin_first_name = r_admin.User_Name(obj)
        self.assertEquals(admin_first_name, r.user.first_name) 

Leave a comment