From 184c9a26a29443e7036dc4f23f8589cc8e4cffd5 Mon Sep 17 00:00:00 2001 From: Christian Zosel Date: Tue, 5 Jul 2022 10:18:56 +0200 Subject: [PATCH] feat: add advanced filters for ACL model --- emeis/core/filters.py | 13 ++++++++++++- emeis/core/tests/test_filters.py | 23 +++++++++++++++++++++++ emeis/core/views.py | 2 +- 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/emeis/core/filters.py b/emeis/core/filters.py index 56443f7..7e7db08 100644 --- a/emeis/core/filters.py +++ b/emeis/core/filters.py @@ -5,7 +5,7 @@ from django_filters.filters import CharFilter from rest_framework import filters -from emeis.core.models import Scope, User +from emeis.core.models import ACL, Scope, User class EmeisSearchFilter(filters.SearchFilter): @@ -64,6 +64,17 @@ class Meta: } +class ACLFilterset(FilterSet): + class Meta: + model = ACL + fields = { + "id": ["exact", "in"], + "user": ["exact", "in"], + "scope": ["exact", "in"], + "role": ["exact", "in"], + } + + class EmeisOrderingFilter(filters.OrderingFilter): """Custom ordering filter for Emeis. diff --git a/emeis/core/tests/test_filters.py b/emeis/core/tests/test_filters.py index 73dfd15..c882daf 100644 --- a/emeis/core/tests/test_filters.py +++ b/emeis/core/tests/test_filters.py @@ -100,6 +100,29 @@ def test_declared_filters( assert ret_users == [] +@pytest.mark.parametrize( + "filter_field, model_attr", + [ + ("user__in", "user_id"), + ("role__in", "role_id"), + ("scope__in", "scope_id"), + ], +) +def test_acl_filters(admin_client, acl_factory, filter_field, model_attr): + acl1, acl2, _ = acl_factory.create_batch(3) + + attr_value_1 = getattr(acl1, model_attr) + attr_value_2 = getattr(acl2, model_attr) + + resp = admin_client.get( + reverse("acl-list"), + {f"filter[{filter_field}]": f"{attr_value_1},{attr_value_2}"}, + ) + + ret_acls = [acl["id"] for acl in resp.json()["data"]] + assert set([str(acl1.pk), str(acl2.pk)]) == set(ret_acls) + + def test_scope_id_filter(admin_client, scope_factory): scope1, _, scope3 = scope_factory.create_batch(3) diff --git a/emeis/core/views.py b/emeis/core/views.py index c0f51f7..25a8410 100644 --- a/emeis/core/views.py +++ b/emeis/core/views.py @@ -187,7 +187,7 @@ class PermissionViewSet(BaseViewset): class ACLViewSet(BaseViewset): serializer_class = serializers.ACLSerializer queryset = models.ACL.objects.all() - filterset_fields = ("user", "scope", "role") + filterset_class = filters.ACLFilterset search_fields = [ "scope__name", "scope__description",