Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter testing

class BusinessPartnerFilter(SilBaseFilter):
    active = django_filters.BooleanFilter(
        name='date_deactivated', lookup_expr='isnull')
    parent_name = django_filters.CharFilter(name='parent__name')
    unmapped = django_filters.BooleanFilter(method='check_if_unmapped')

I have added the field 'unmapped' above and created the method filter below. Can someone please help me to write tests for the filter. I'm stuck.

class Meta(object):
    model = models.BusinessPartner
    fields = [
        'name', 'bp_type', 'slade_code', 'parent', 'national_identifier',
        'active', 'parent_name', 'unmapped'
    ]

    def check_if_unmapped(self, queryset, field, value):
        if value:
            exclude_bps = [record.id for record in queryset if record.mapped == 0 and record.unmapped == 0]
            return queryset.exclude(id__in=exclude_bps)
        return queryset
like image 402
NoObiE Avatar asked Aug 18 '17 12:08

NoObiE


1 Answers

You can either test the filter method in isolation, or test the evaluation of FilterSet.qs.

To test the filter method, you don't necessarily need a fully initialized FilterSet.

qs = BusinessPartner.objects.all()
f = BusinessPartnerFilter()
result = f.check_if_unmapped(qs, 'unmapped', True)
# assert something about the result

That said, it's not much more difficult to fully initialize the FilterSet and check the .qs.

qs = BusinessPartner.objects.all()
f = BusinessPartnerFilter(data={'unmapped': 'True'}, queryset=qs)
result = f.qs
# assert something about the result
like image 161
Sherpa Avatar answered Oct 30 '22 02:10

Sherpa