schacki avatar schacki committed 6bbb25b

modified the ifhasperm templatetag and added tests for it

Comments (0)

Files changed (3)

permissions/exceptions.py

     
 class PermissionNameExists(Exception):
     pass    
+    
+class TooManyArguments(Exception):
+    pass

permissions/templatetags/permissions_tags.py

     @classmethod
     def handle_token(cls, parser, token):
         bits = token.contents.split()
-        if len(bits) != 2:
+        if len(bits) != 3:
             raise template.TemplateSyntaxError(
                 "'%s' tag takes one argument" % bits[0])
         end_tag = 'endifhasperm'
         else:
             nodelist_false = ""
 
-        return cls(bits[1], nodelist_true, nodelist_false)
+        return cls(bits[1], bits[2], nodelist_true, nodelist_false)
 
-    def __init__(self, codename, nodelist_true, nodelist_false):
+    def __init__(self, codename, obj, nodelist_true, nodelist_false):
         self.codename = codename
+        self.obj=template.Variable(obj)
         self.nodelist_true = nodelist_true
         self.nodelist_false = nodelist_false
 
     def render(self, context):
-        obj = context.get("obj")
-        request = context.get("request")
-        if permissions.utils.has_permission(obj, request.user, self.codename):
+        obj = self.obj.resolve(context)
+        try:
+            user = context.get('user') or context.get('request').user
+        except:
+            user=context.get('request').user
+        if permissions.utils.has_permission(obj, user, self.codename):
             return self.nodelist_true.render(context)
         else:
-            return self.nodelist_false
+            return self.nodelist_false.render(context)
 
 @register.tag
 def ifhasperm(parser, token):

permissions/tests.py

 from django.test import TestCase
 from django.test.client import Client
 from django.contrib.contenttypes.models import ContentType
+from django.http import HttpResponseRedirect, HttpResponseForbidden
+from django.template import Context, Template, Variable
 
 # permissions imports
 from permissions.models import Permission
 
 import permissions.utils
 import permissions.settings
+from permissions.decorator import permission_required
 
 
 
 
             permissions.utils.reset(self.page_1)        
 
+class DecoratorTestCase(TestCase):
+    def setUp(self):
+        self.role = permissions.utils.register_role("Viewer")
+        self.permission = permissions.utils.register_permission("View", "view")        
+        self.user = User.objects.create(username="john")
+        self.page_1 = FlatPage.objects.create(url="/page-1/", title="Page 1")
+        self.page_2 = FlatPage.objects.create(url="/page-2/", title="Page 2") 
+        class Dummy(object):
+            user=self.user
+        self.request=Dummy()      
+        if permissions.settings.ROLES_ENABLED:     
+            permissions.utils.add_role(self.user, self.role)
+            permissions.utils.grant_permission(self.page_1,self.role,'view')
+        else:
+            permissions.utils.grant_permission(self.page_1,self.user,'view')
+
+    def view_func(self,request,*args,**kwargs):
+        return 'success'
+        
+    def test_request_args_arguments(self):
+        decorated_function=permission_required('flatpages.FlatPage.view',('url',0))(self.view_func)
+        result=decorated_function(self.request,'/page-1/')
+        self.assertEqual(result,'success')
+        result=decorated_function(self.request,'/page-2/')
+        self.assertEqual(isinstance(result,HttpResponseForbidden),True)
+        
+    def test_request_kwargs_arguments(self):
+        decorated_function=permission_required('flatpages.FlatPage.view',('url','url'))(self.view_func)
+        result=decorated_function(self.request,url='/page-1/')
+        self.assertEqual(result,'success')
+        result=decorated_function(self.request,url='/page-2/')
+        self.assertEqual(isinstance(result,HttpResponseForbidden),True)
+        
+    def test_wrong_decorator_kwargs(self):
+        with self.assertRaises(ValueError) as cm:
+            permission_required('flatpages.FlatPage.view',('url','url'),test='test')(self.view_func)
+
+    def test_wrong_permission_syntax(self):
+        with self.assertRaises(ValueError) as cm:
+            permission_required('flatpages.FlatPage_view',('url','url'),test='test')(self.view_func)        
+
+class TemplateTagTestCase(TestCase):
+    def setUp(self):
+        """
+        """
+        self.template_string='{% load permissions_tags %}{% ifhasperm view flatpage %}yes{% else %}no{%endifhasperm%}'
+        self.role = permissions.utils.register_role("Viewer")
+        self.permission = permissions.utils.register_permission("View", "view")        
+        self.user = User.objects.create(username="john")
+        self.page_1 = FlatPage.objects.create(url="/page-1/", title="Page 1")
+        self.page_2 = FlatPage.objects.create(url="/page-2/", title="Page 2") 
+        class Dummy(object):
+            user=self.user
+        self.request=Dummy()      
+        if permissions.settings.ROLES_ENABLED:     
+            permissions.utils.add_role(self.user, self.role)
+            permissions.utils.grant_permission(self.page_1,self.role,'view')
+        else:
+            permissions.utils.grant_permission(self.page_1,self.user,'view')
+        
+        
+    def test_permission_user(self):
+        result=Template(self.template_string).render(Context({'flatpage':self.page_1,'user':self.user}))
+        self.assertEqual(result,'yes')
+        result=Template(self.template_string).render(Context({'flatpage':self.page_2,'user':self.user}))
+        self.assertEqual(result,'no')   
+    
+    def test_permission_request_user(self):
+        result=Template(self.template_string).render(Context({'flatpage':self.page_1,'request':self.request}))
+        self.assertEqual(result,'yes')
+        result=Template(self.template_string).render(Context({'flatpage':self.page_2,'request':self.request}))
+        self.assertEqual(result,'no')
+        
+        
 class RegistrationTestCase(TestCase):
     """Tests the registration of different components.
     """
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.