在admin.py中测试自定义过滤器

时间:2013-05-25 15:57:16

标签: django django-admin django-tests

我的admin.py文件中有以下过滤条件:

class parentCategoryFilter(admin.SimpleListFilter):
    title = 'parent category'
    parameter_name = 'parent_category'

    def lookups(self, request, model_admin):
        first_level_categories = model_admin.get_queryset(request).filter(parent_category__isnull=True)

        if first_level_categories:

            lookups = (('none', 'None'),)

            for first_level_category in first_level_categories:
                lookups += ((first_level_category.id, first_level_category.name),)

            return lookups

    def queryset(self, request, queryset):
        if self.value() == 'none':
            return queryset.filter(parent_category__isnull=True)
        elif self.value():
            try:
                return queryset.filter(parent_category=int(self.value()))
            except (ValueError, TypeError):
                return queryset.none()
        else:
            pass

我想在我的tests.py文件中测试它,但是在尝试实例化类时,它开始向我询问大约5个__init__参数。是否可以测试此过滤器功能?

2 个答案:

答案 0 :(得分:8)

感谢karthikr和大量阅读,我提出了以下解决方案(使用Django的Pool示例):

过滤方法定义如下:

class WasPublishedRecentlyFilter(admin.SimpleListFilter):
    title = 'Was published recently'
    parameter_name = 'published_recently'

    def lookups(self, request, model_admin):
        return (
            ('yes', 'Yes',),
            ('no', 'No',),
        )

    def queryset(self, request, queryset):
        if self.value() == 'yes':
            #filter logic
        elif self.value() == 'no':
            #filter logic
        elif self.value():
            return queryset.none() 

过滤器的测试:

def test_filter(self):
    Poll.objects.create(question='Sup?', pub_date=timezone.now())
    Poll.objects.create(question='How you doing?', pub_date=timezone.now() - datetime.timedelta(days=1))

    filter = admin.WasPublishedRecentlyFilter(None, {'published_recently':'yes'}, Poll, admin.PollAdmin)
    poll = filter.queryset(None, Poll.objects.all())[0]
    self.assertEqual(poll.question, 'Sup?')

    filter = admin.WasPublishedRecentlyFilter(None, {'published_recently':'no'}, Poll, admin.PollAdmin)
    poll = filter.queryset(None, Poll.objects.all())[0]
    self.assertEqual(poll.question, 'How you doing?')

输出:

Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.124s

OK
Destroying test database for alias 'default'...

答案 1 :(得分:3)

__init__所需的5个参数来自admin.SimpleListFilter,其__init__定义为:(Source

def __init__(self, request, params, model, model_admin):

您可以传递这些参数来测试过滤器