Unittest Django模型权限

时间:2013-11-20 05:25:36

标签: python django unit-testing

如何在模型中测试模型自定义权限?


如果用户在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'),
        )

1 个答案:

答案 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