can't change user permissions during unittest in django

这一生的挚爱 提交于 2019-12-04 09:03:11
Alasdair

If you look at the source code for the ModelBackend, you can see that Django does cache the permissions on the user object.

You could try wiping the cache, but that could break your tests if the caching mechanism changes in future. The easiest thing to do is to refetch 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))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!