Source

django-perms / perms / tests.py

from django.test import TestCase
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType

from perms.models import ObjectPermission
from django.core.exceptions import ValidationError

class SimpleTest(TestCase):
    def setUp(self):
        self.user = User.objects.create_user('test', 'test@abc.com', 'abc')
        self.ct = ContentType.objects.get_for_model(self.user)
    
    def add_perm(self, name):
        op = ObjectPermission(
            user=self.user,
            action=name,
            content_type=self.ct,
            object_id=self.user.id,
        )
        op.clean()
        return op.save()
    
    def test_basic_addition(self):
        self.assertFalse(self.user.has_perm('view', self.user))
        self.add_perm('view')
        self.assertTrue(self.user.has_perm('view', self.user))
        
    def test_bad_perm_addition(self):
        self.assertFalse(self.user.has_perm('no_go', self.user))
        try:
            self.add_perm('no_go')
        except ValidationError:
            pass
        self.assertFalse(self.user.has_perm('no_go', self.user))
        
    def test_bad_objectid_addition(self):
        op = ObjectPermission(
            user=self.user,
            action='view',
            content_type=self.ct,
            object_id=9999,
        )
        try:
            op.clean()
            op.save()
        except ValidationError:
            pass
        self.assertFalse(self.user.has_perm('view', self.user))