def test_cache(self): checker = ObjectPermissionChecker(self.mum) with mock.patch('guardian.tests.signals.signal_get_perms_user', return_value=[], autospec=True) as mocked_handler: get_perms.connect(mocked_handler, sender=User, dispatch_uid='test_cache_mocked_handler') checker.has_perm('a_custom_perm', self.user) checker.has_perm('another_custom_perm', self.user) self.assertEqual(mocked_handler.call_count, 1)
from guardian.signals import get_perms from guardian.tests.core_test import ObjectPermissionTestCase from guardian.tests.tags_test import render def signal_get_perms_user(sender, user, obj, **kwargs): """ return the permissions of @user on object @obj """ if obj.username == 'jack': if user.username in ('mum', 'dad'): return get_perm_codenames_for_model(User) if user.username == 'bob': return ['another_custom_perm', ] return [] get_perms.connect(signal_get_perms_user, sender=User, dispatch_uid='guardian.test.signals.signal_get_perms_user') class GetPermsSignalTest(ObjectPermissionTestCase): def setUp(self): super(GetPermsSignalTest, self).setUp() self.mum, created = User.objects.get_or_create(username='******') self.dad, created = User.objects.get_or_create(username='******') self.bob, created = User.objects.get_or_create(username='******') Permission.objects.create( name='Can do something', codename='a_custom_perm', content_type=ContentType.objects.get_for_model(User) )