Skip to content

Commit

Permalink
feat: add advanced filters for ACL model
Browse files Browse the repository at this point in the history
  • Loading branch information
czosel committed Jul 5, 2022
1 parent 84fa0af commit 184c9a2
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
13 changes: 12 additions & 1 deletion emeis/core/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions emeis/core/tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion emeis/core/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 184c9a2

Please sign in to comment.