Search code examples
djangounit-testingpython-unittestassertdjango-unittest

How to check and see if an output contains the desired elements from any list or not?


I am trying to write tests for a particular app in django using the python's unittest library.

def test_permissions_for_admin(self):
    admin = Group.objects.get(name='Administrator')
    permisisons = admin.permissions.all()
    admin_permissions = ['add_ipaddress', 'change_ipaddress', 'delete_ipaddress', 'view_ipaddress', 'add_subnet', 'change_subnet', 'delete_subnet', 'view_subnet']
    
    for p in permissions:
        print(p.codename)
    
    for p in permissions:
        self.assertIn(p.codename, admin_permissions)

The Above code prints this, OUTPUT:

change_emailaddress
delete_emailaddress
view_emailaddress
add_ipaddress
change_ipaddress
delete_ipaddress
view_ipaddress
add_subnet
change_subnet
delete_subnet
view_subnet
view_group
change_organization
change_organizationowner
add_organizationuser
change_organizationuser
delete_organizationuser
view_organizationuser
add_user
change_user
delete_user
view_user

Whereas What I am trying to check is that, all the permissions present from the variable admin_permissions are present in this output or not.

I have tried using the assertIn, assertEqual, & assertTrue methods but it doesn't seem to work here. Is there anything else I could look for or any method present which I am not aware of to solve such kind of issues.


Solution

  • If you want to check if the admin has all the permissions, you need to do this the other way around, so:

    perms = list(admin.permissions.values_list('codename', flat=True))
    for p in admin_permissions:
        self.assertIn(p, perms)

    we here thus check that for each item in admin_permissions, it is a member of perms: the codenames of the .permissions of admin.