Tests for checking the permissions of a group
Asked Answered
L

1

0

I am trying to write tests for an app to check that a group has the required permission for a particular model or not in django.

App Name:- Blog
Model Name:- Post

I am able to query all the permissions but having a tough time figuring out how can I write the test script for it. Here's the script:-

def test_group_permission(self):
        for group in Group.objects.all():
            permissions = group.permissions.all()
            print(permissions)

With the above code, this is the output I get:-

<QuerySet [
<Permission: blog | post | Can add post>, 
<Permission: blog | post | Can change post>, 
<Permission: blog | post | Can delete post>, 
<Permission: blog | post | Can view post>
]>

Now, how can I write a proper test(s) script for checking to see if the required permissions are present in a group for that particular model, if it does it returns True else False

Lungki answered 5/12, 2020 at 11:2 Comment(1)
you could check permissions name that you are expecting to be available for your objectIncapacious
U
1

The Django documentation is terrible for explaining the relationship between user and group permissions. I think the confusion is from the fact that Group is some kind of appendage for User and Django assumes, incorrectly, that people will usually be checking permissions on the User object.

Try this if you want strings in the same way User.objects.get(name = ...).get_group_permissions() gives permissions as strings:

    def test_group_permission(self):
            for group in Group.objects.all():
                permissions = group.permissions.all()
                print([i.content_type.app_label + '.' + i.codename for i in group.permissions.all()])
Uno answered 8/5, 2021 at 5:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.