如果用户在user.has_perm('foo.add_bar')
中拥有add_bar
权限,我通常可以bar
进行测试。
但如果foo.has_perm('add_bar')
拥有foo
权限,则此add_bar
似乎不起作用。
AttributeError:'foo'对象没有属性'has_perm'
我想做的是
self.assertTrue(foo.has_perm('add_bar'))
我的foo模型如下所示:
class Foo(models.Model):
name = models.CharField(max_length=255)
bar = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True,
editable=False,
db_index=True)
class Meta:
permissions = (
('add_bar', 'Can add Bar'),
)
答案 0 :(得分:0)
我使用辅助函数解决了问题并将其归因于模型Foo.has_perm = model_has_perm_helper
#imports omitted
class FooTest(TestCase):
"""
Test model and users permissions. Model level and object level
"""
def setUp(self):
# Do setup stuff here
pass
def test_permissions(self):
Foo.has_perm = model_has_perm_helper
self.assertTrue(union.has_perm('add_wedding'))
# do others stuffs here, like check if user has that permission and such
def model_has_perm_helper(model, perm):
"""
Helper function adds ability to call has_perm in model class
"""
try:
content_type = ContentType.objects.get_for_model(model)
Permission.objects.get(content_type=content_type, codename=perm)
except: #DoesNotExist error
return False
return True