Cannot change user permissions during unittest in django

Finally, I decided to do some tests for my applications, but I was stuck on testing if the user can change another user (depends on the type of user - I use django rules to be able to do logical permissions checks, but that doesn't matter)

Here is the code that I still have

class RulesAndPermissionsTests(TestCase): fixtures = ['auth_no_permissions.json', 'profiles.json', 'rules.json'] def setUp(self): self.c = Client() self.user = User.objects.get(username="estagiario") self.non_staff = User.objects.get(username="fisica") self.admin = User.objects.get(username="admin") login = self.c.login(username='estagiario', password='estagiario') def test_can_change_non_staff_users(self): self.assertFalse(self.user.has_perm('logical_change_user', self.non_staff.profile)) # can't change non staff users without permission # now add the permission and test it again self.user.user_permissions.add(Permission.objects.get(codename='change_user')) print self.user.get_all_permissions() # prints set([]) self.assertTrue(self.user.has_perm('logical_change_user', self.non_staff.profile)) 

Even after adding permission, my user still does not have permissions. Is it because I am not allowed to create anything during tests (is this bad practice?)? Or does django cache permissions in some way? If I add permission to setUp, it will work, but I would like to change it during the same test (testing with permission and without permission).

Thanks in advance!

+4
django django-testing django-permissions
source share
1 answer

If you look at the source code for ModelBackend , you will see that Django ModelBackend permissions for the user object.

You can try to clear the cache, but this can break your tests if the caching mechanism changes in the future. The easiest way to do this is to restore the user from the database in your test.

 from django.contrib.auth.models import Permission def test_can_change_non_staff_users(self): self.assertFalse(self.user.has_perm('logical_change_user', self.non_staff.profile)) # can't change non staff users without permission # now add the permission and test it again self.user.user_permissions.add(Permission.objects.get(codename='change_user')) # refetch user from the database self.user = User.objects.get(pk=self.user.pk) print self.user.get_all_permissions() # should now include new permission self.assertTrue(self.user.has_perm('logical_change_user', self.non_staff.profile)) 
+14
source share

All Articles