[英]Unittest Django Model Permissions
I can normally do user.has_perm('foo.add_bar')
for test if a user has add_bar
permission in bar
. 我通常可以执行
user.has_perm('foo.add_bar')
来测试用户是否在bar
具有add_bar
权限。
but this one don't seems to work foo.has_perm('add_bar')
for check if foo
has add_bar
permission. 但这似乎不起作用
foo.has_perm('add_bar')
检查foo
是否具有add_bar
权限。
AttributeError: 'foo' object has no attribute 'has_perm'
AttributeError:'foo'对象没有属性'has_perm'
What I'm trying to do is 我想做的是
self.assertTrue(foo.has_perm('add_bar'))
My foo model looks like this: 我的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'),
)
I solved the problem using an helper function and attributing it to the model Foo.has_perm = model_has_perm_helper
我使用辅助函数解决了该问题,并将其归因于模型
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.