Python Unittest Django模型权限 如何在模型中测试模型自定义权限?
如果用户在Python Unittest Django模型权限 如何在模型中测试模型自定义权限?,python,django,unit-testing,Python,Django,Unit Testing,如果用户在bar中拥有add\bar权限,我通常可以对user.has\u perm('foo.add\u bar')进行测试 但是这个似乎不起作用。has_perm('add_bar')检查foo是否具有add_bar权限 AttributeError:“foo”对象没有属性“has\u perm” 我想做的是 self.assertTrue(foo.has_perm('add_bar')) 我的foo模型如下所示: class Foo(models.Model): name = m
bar
中拥有add\bar
权限,我通常可以对user.has\u perm('foo.add\u bar')
进行测试
但是这个似乎不起作用。has_perm('add_bar')检查foo
是否具有add_bar
权限
AttributeError:“foo”对象没有属性“has\u 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'),
)
我使用一个helper函数解决了这个问题,并将其归因于model
Foo.has\u perm=model\u has\u perm\u 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
什么是
foo
,如果它是一个模型,那么它就没有权限,因为只有用户有权限。否则,您需要将权限
添加到模型元选项中。