[Zope-Checkins] CVS: Zope3/lib/python/Zope/App/Security/tests - PermissionService.py:1.2 RolePermissionManager.py:1.2 RoleService.py:1.2 TestModule.py:1.2 TestModuleHookup.py:1.2 __init__.py:1.2 testAnnotationPrincipalPermissionManager.py:1.2 testAnnotationPrincipalRoleManager.py:1.2 testAnnotationRolePermissionManager.py:1.2 testBasicAuthAdapter.py:1.2 testLoginPassword.py:1.2 testPermissionRegistry.py:1.2 testPrincipalPermissionManager.py:1.2 testPrincipalPermissionView.py:1.2 testPrincipalRegistry.py:1.2 testPrincipalRoleManager.py:1.2 testPrincipalRoleView.py:1.2 testProtectClass.py:1.2 testProtectSubClass.py:1.2 testRolePermissionManager.py:1.2 testRolePermissionView.py:1.2 testRoleRegistry.py:1.2 testSecurityDirectives.py:1.2 testSettings.py:1.2 testZSP.py:1.2
Jim Fulton
jim@zope.com
Mon, 10 Jun 2002 19:28:51 -0400
Update of /cvs-repository/Zope3/lib/python/Zope/App/Security/tests
In directory cvs.zope.org:/tmp/cvs-serv17445/lib/python/Zope/App/Security/tests
Added Files:
PermissionService.py RolePermissionManager.py RoleService.py
TestModule.py TestModuleHookup.py __init__.py
testAnnotationPrincipalPermissionManager.py
testAnnotationPrincipalRoleManager.py
testAnnotationRolePermissionManager.py testBasicAuthAdapter.py
testLoginPassword.py testPermissionRegistry.py
testPrincipalPermissionManager.py
testPrincipalPermissionView.py testPrincipalRegistry.py
testPrincipalRoleManager.py testPrincipalRoleView.py
testProtectClass.py testProtectSubClass.py
testRolePermissionManager.py testRolePermissionView.py
testRoleRegistry.py testSecurityDirectives.py testSettings.py
testZSP.py
Log Message:
Merged Zope-3x-branch into newly forked Zope3 CVS Tree.
=== Zope3/lib/python/Zope/App/Security/tests/PermissionService.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""PermissionService implementation for testing
+
+$Id$
+"""
+
+from Zope.App.Security.IPermissionService import IPermissionService
+from Zope.App.Security.IPermission import IPermission
+
+class Permission:
+
+ __implements__ = IPermission
+
+ def __init__(self, id, title): self._id, self._title = id, title
+ def getId(self): return self._id
+ def getTitle(self): return self._title
+ def getDescription(self): return ''
+
+class PermissionService:
+
+ __implements__ = IPermissionService
+
+ def __init__(self, **kw):
+ self._permissions = r = {}
+ for id, title in kw.items(): r[id]=Permission(id, title)
+
+ # Implementation methods for interface
+ # Zope.App.Security.IPermissionService.
+
+ def getPermission(self, rid):
+ '''See interface IPermissionService'''
+ return self._permissions.get(rid)
+
+ def getPermissions(self):
+ '''See interface IPermissionService'''
+ return self._permissions.values()
=== Zope3/lib/python/Zope/App/Security/tests/RolePermissionManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""
+Test IRolePermissionManager class.
+
+$Id$
+"""
+
+from Zope.App.Security.IRolePermissionManager import IRolePermissionManager
+from Zope.App.Security.Settings import Allow, Assign
+
+class RolePermissionManager:
+
+ __implements__ = IRolePermissionManager
+
+ def __init__(self, **rp):
+ self._rp = rp
+
+ # Implementation methods for interface
+ # Zope.App.Security.IRolePermissionManager.
+
+ def getRolesForPermission(self, permission):
+ '''See interface IRolePermissionMap'''
+ r=[]
+ for role, permissions in self._rp.items():
+ if permission in permissions: r.append((role, Allow))
+ return r
+
+ def getPermissionAcquired(self, permission):
+ '''See interface IRolePermissionMap'''
+ return 1
+
+ def getPermissionsForRole(self, role):
+ '''See interface IRolePermissionMap'''
+ return [(perm, Allow) for perm in self._rp[role]]
+
+ def setPermissionAcquired(self, permission, flag):
+ '''See interface IRolePermissionManager'''
+ raise TypeError
+
+ def unsetPermissionFromRole(self, permission, role):
+ '''See interface IRolePermissionManager'''
+ permissions = self._rp.get(role, ())
+ if permission in permissions:
+ permissions.remove(permission)
+ if not permissions:
+ # XXX: this del removed by Steve and Casey
+ # in order to get the PermissionsForRole
+ # view unit tests to work correctly.
+ #
+ # Why is this del here?
+ #
+ # It doesn't seem to break anything to remove
+ # it, like this!
+ #del self._rp[role]
+ pass
+
+
+ def grantPermissionToRole(self, permission, role):
+ '''See interface IRolePermissionManager'''
+ if role in self._rp:
+ if permission not in self._rp[role]:
+ self._rp[role].append(permission)
+ else:
+ self._rp[role] = [permission]
+
=== Zope3/lib/python/Zope/App/Security/tests/RoleService.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""RoleService implementation for testing
+
+$Id$
+"""
+
+from Zope.App.Security.IRoleService import IRoleService
+from Zope.App.Security.IRole import IRole
+
+class Role:
+
+ __implements__ = IRole
+
+ def __init__(self, id, title): self._id, self._title = id, title
+ def getId(self): return self._id
+ def getTitle(self): return self._title
+ def getDescription(self): return ''
+
+class RoleService:
+
+ __implements__ = IRoleService
+
+ def __init__(self, **kw):
+ self._roles = r = {}
+ for id, title in kw.items(): r[id]=Role(id, title)
+
+ # Implementation methods for interface
+ # Zope.App.Security.IRoleService.
+
+ def getRole(self, rid):
+ '''See interface IRoleService'''
+ return self._roles.get(rid)
+
+ def getRoles(self):
+ '''See interface IRoleService'''
+ return self._roles.values()
=== Zope3/lib/python/Zope/App/Security/tests/TestModule.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""This empty module is for containing objects used in the course of tests.
+
+(There is a problem with the way the unit tests interact with the modules
+being tests, so the objects can't be expected to show up in place.)"""
=== Zope3/lib/python/Zope/App/Security/tests/TestModuleHookup.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Preliminaries to hookup a test suite with the external TestModule.
+
+This is necessary because the test framework interferes with seeing changes in
+the running modules via the module namespace. This enables having some
+subject classes, instances, permissions, etc, that don't live in the test
+modules, themselves."""
+
+from Interface import Interface
+
+PREFIX = "Zope.App.Security.tests.TestModule."
+import Zope.App.Security.tests.TestModule as TestModule
+TestModule.test_class = None
+class I(Interface):
+ def m1():
+ pass
+ def m2():
+ pass
+
+class I2(I):
+ def m4():
+ pass
+
+
+TestModule.I = I
+TestModule.I2 = I2
+
+template_bracket = """<zopeConfigure
+ xmlns="http://namespaces.zope.org/zope"
+ xmlns:security='http://namespaces.zope.org/security'>
+ %s
+</zopeConfigure>"""
=== Zope3/lib/python/Zope/App/Security/tests/__init__.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+""" Zope.App.Security unit tests """
=== Zope3/lib/python/Zope/App/Security/tests/testAnnotationPrincipalPermissionManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test handler for AnnotationPrincipalPermissionManager module."""
+
+import sys
+import unittest
+
+from Zope.App.OFS.Annotation.IAttributeAnnotatable import IAttributeAnnotatable
+from Zope.ComponentArchitecture import getService
+from Zope.App.OFS.Annotation.IAnnotations import IAnnotations
+from Zope.App.OFS.Annotation.AttributeAnnotations import AttributeAnnotations
+from Zope.App.Security.PermissionRegistry \
+ import permissionRegistry as permregistry
+from Zope.App.Security.PrincipalRegistry \
+ import principalRegistry as prinregistry
+from Zope.App.Security.AnnotationPrincipalPermissionManager \
+ import AnnotationPrincipalPermissionManager
+from Zope.App.Security.Settings import Allow, Deny, Unset
+from Zope.ComponentArchitecture.tests.PlacelessSetup import PlacelessSetup
+
+class Manageable:
+ __implements__ = IAttributeAnnotatable
+
+class Test(PlacelessSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacelessSetup.setUp(self)
+ getService(None,"Adapters").provideAdapter(
+ IAttributeAnnotatable, IAnnotations,
+ AttributeAnnotations)
+
+ def _make_principal(self, id=None, title=None):
+ p = prinregistry.definePrincipal(
+ id or 'APrincipal',
+ title or 'A Principal',
+ login = id or 'APrincipal')
+ return p.getId()
+
+ def testUnboundPrincipalPermission(self):
+ manager = AnnotationPrincipalPermissionManager(Manageable())
+ permission = permregistry.definePermission('APerm', 'title')
+ permission = permission.getId()
+ principal = self._make_principal()
+ self.assertEqual(manager.getPrincipalsForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal), [])
+
+ def testPrincipalPermission(self):
+ manager = AnnotationPrincipalPermissionManager(Manageable())
+ permission = permregistry.definePermission('APerm', 'title')
+ permission = permission.getId()
+ principal = self._make_principal()
+
+ # check that an allow permission is saved correctly
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Allow)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Allow)])
+
+ # check that the allow permission is removed.
+ manager.unsetPermissionForPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal), [])
+
+ # now put a deny in there, check it's set.
+ manager.denyPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Deny)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Deny)])
+
+ # test for deny followed by allow . The latter should override.
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Allow)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Allow)])
+
+ # check that allow followed by allow is just a single allow.
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Allow)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Allow)])
+
+ # check that two unsets in a row quietly ignores the second one.
+ manager.unsetPermissionForPrincipal(permission, principal)
+ manager.unsetPermissionForPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal), [])
+
+ # check the result of getSetting() when it's empty.
+ self.assertEqual(manager.getSetting(permission, principal), Unset)
+
+ # check the result of getSetting() when it's allowed.
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getSetting(permission, principal), Allow)
+
+ # check the result of getSetting() when it's denied.
+ manager.denyPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getSetting(permission, principal), Deny)
+
+ def testManyPermissionsOnePrincipal(self):
+ manager = AnnotationPrincipalPermissionManager(Manageable())
+ perm1 = permregistry.definePermission('Perm One', 'title').getId()
+ perm2 = permregistry.definePermission('Perm Two', 'title').getId()
+ prin1 = self._make_principal()
+ manager.grantPermissionToPrincipal(perm1, prin1)
+ manager.grantPermissionToPrincipal(perm2, prin1)
+ perms = manager.getPermissionsForPrincipal(prin1)
+ self.assertEqual(len(perms), 2)
+ self.failUnless((perm1,Allow) in perms)
+ self.failUnless((perm2,Allow) in perms)
+ manager.denyPermissionToPrincipal(perm2, prin1)
+ perms = manager.getPermissionsForPrincipal(prin1)
+ self.assertEqual(len(perms), 2)
+ self.failUnless((perm1,Allow) in perms)
+ self.failUnless((perm2,Deny) in perms)
+
+ def testManyPrincipalsOnePermission(self):
+ manager = AnnotationPrincipalPermissionManager(Manageable())
+ perm1 = permregistry.definePermission('Perm One', 'title').getId()
+ prin1 = self._make_principal()
+ prin2 = self._make_principal('Principal 2', 'Principal Two')
+ manager.grantPermissionToPrincipal(perm1, prin1)
+ manager.denyPermissionToPrincipal(perm1, prin2)
+ principals = manager.getPrincipalsForPermission(perm1)
+ self.assertEqual(len(principals), 2)
+ self.failUnless((prin1,Allow) in principals)
+ self.failUnless((prin2,Deny) in principals)
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testAnnotationPrincipalRoleManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test handler for PrincipalRoleManager module."""
+
+import sys
+import unittest
+
+from Zope.App.OFS.Annotation.IAttributeAnnotatable import IAttributeAnnotatable
+from Zope.ComponentArchitecture import getService
+from Zope.App.OFS.Annotation.IAnnotations import IAnnotations
+from Zope.App.OFS.Annotation.AttributeAnnotations import AttributeAnnotations
+from Zope.App.Security.RoleRegistry import roleRegistry as rregistry
+from Zope.App.Security.PrincipalRegistry import principalRegistry as pregistry
+from Zope.App.Security.AnnotationPrincipalRoleManager \
+ import AnnotationPrincipalRoleManager
+from Zope.App.Security.Settings import Assign, Remove
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup import PlacefulSetup
+
+class Manageable:
+ __implements__ = IAttributeAnnotatable
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+ getService(None,"Adapters").provideAdapter(
+ IAttributeAnnotatable, IAnnotations,
+ AttributeAnnotations)
+
+ def _make_principal(self, id=None, title=None):
+ p = pregistry.definePrincipal(
+ id or 'APrincipal',
+ title or 'A Principal',
+ login = id or 'APrincipal')
+ return p.getId()
+
+ def testUnboundPrincipalRole(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role), [])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [])
+
+ def testPrincipalRoleAssign(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ principalRoleManager.assignRoleToPrincipal(role, principal)
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role),
+ [(principal,Assign)])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [(role,Assign)])
+
+ def testPrincipalRoleRemove(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ principalRoleManager.removeRoleFromPrincipal(role, principal)
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role),
+ [(principal,Remove)])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [(role,Remove)])
+
+ def testPrincipalRoleUnset(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ principalRoleManager.removeRoleFromPrincipal(role, principal)
+ principalRoleManager.unsetRoleForPrincipal(role, principal)
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role),
+ [])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [])
+
+ def testManyRolesOnePrincipal(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ role2 = rregistry.defineRole('Role Two', 'Role #2').getId()
+ prin1 = self._make_principal()
+ principalRoleManager.assignRoleToPrincipal(role1, prin1)
+ principalRoleManager.assignRoleToPrincipal(role2, prin1)
+ roles = principalRoleManager.getRolesForPrincipal(prin1)
+ self.assertEqual(len(roles), 2)
+ self.failUnless((role1,Assign) in roles)
+ self.failUnless((role2,Assign) in roles)
+
+ def testManyPrincipalsOneRole(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ prin1 = self._make_principal()
+ prin2 = self._make_principal('Principal 2', 'Principal Two')
+ principalRoleManager.assignRoleToPrincipal(role1, prin1)
+ principalRoleManager.assignRoleToPrincipal(role1, prin2)
+ principals = principalRoleManager.getPrincipalsForRole(role1)
+ self.assertEqual(len(principals), 2)
+ self.failUnless((prin1,Assign) in principals)
+ self.failUnless((prin2,Assign) in principals)
+
+ def testPrincipalsAndRoles(self):
+ principalRoleManager = AnnotationPrincipalRoleManager(Manageable())
+ principalsAndRoles = principalRoleManager.getPrincipalsAndRoles()
+ self.assertEqual(len(principalsAndRoles), 0)
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ role2 = rregistry.defineRole('Role Two', 'Role #2').getId()
+ prin1 = self._make_principal()
+ prin2 = self._make_principal('Principal 2', 'Principal Two')
+ principalRoleManager.assignRoleToPrincipal(role1, prin1)
+ principalRoleManager.assignRoleToPrincipal(role1, prin2)
+ principalRoleManager.assignRoleToPrincipal(role2, prin1)
+ principalsAndRoles = principalRoleManager.getPrincipalsAndRoles()
+ self.assertEqual(len(principalsAndRoles), 3)
+ self.failUnless((role1,prin1,Assign) in principalsAndRoles)
+ self.failUnless((role1,prin2,Assign) in principalsAndRoles)
+ self.failUnless((role2,prin1,Assign) in principalsAndRoles)
+
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testAnnotationRolePermissionManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+from Zope.App.Security.AnnotationRolePermissionManager \
+ import AnnotationRolePermissionManager
+from Zope.App.OFS.Annotation.IAttributeAnnotatable import IAttributeAnnotatable
+from Zope.App.OFS.Annotation.IAnnotations import IAnnotations
+from Zope.App.OFS.Annotation.AttributeAnnotations import AttributeAnnotations
+from Zope.ComponentArchitecture \
+ import getServiceManager, getService
+from Zope.App.Security.IRoleService import IRoleService
+from Zope.App.Security.IPermissionService import IPermissionService
+from Zope.App.Security.RoleRegistry import roleRegistry
+from Zope.App.Security.PermissionRegistry import permissionRegistry
+from Zope.App.Security.Settings import Allow, Deny
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup \
+ import PlacefulSetup
+
+import unittest, sys
+
+class Manageable:
+ __implements__ = IAttributeAnnotatable
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+ defineService=getServiceManager(None).defineService
+ provideService=getServiceManager(None).provideService
+ defineService('RoleService', IRoleService)
+ defineService('PermissionService', IPermissionService)
+ provideService('RoleService', roleRegistry)
+ provideService('PermissionService', permissionRegistry)
+ provideAdapter=getService(None,"Adapters").provideAdapter
+ provideAdapter(IAttributeAnnotatable, IAnnotations,
+ AttributeAnnotations)
+
+ read = permissionRegistry.definePermission('read', 'Read Something')
+ self.read = read.getId()
+
+ write = permissionRegistry.definePermission('write', 'Write Something')
+ self.write = write.getId()
+
+ peon = roleRegistry.defineRole('peon', 'Poor Slob')
+ self.peon = peon.getId()
+
+ manager = roleRegistry.defineRole('manager', 'Supreme Being')
+ self.manager = manager.getId()
+
+ def testNormal(self):
+ obj = Manageable()
+ mgr = AnnotationRolePermissionManager(obj)
+ mgr.grantPermissionToRole(self.read,self.manager)
+ mgr.grantPermissionToRole(self.write,self.manager)
+ mgr.grantPermissionToRole(self.write,self.manager)
+
+ mgr.grantPermissionToRole(self.read,self.peon)
+
+ l = list(mgr.getPermissionsForRole(self.manager))
+ self.failUnless( (self.read, Allow) in l )
+ self.failUnless( (self.write, Allow) in l )
+
+ l = list(mgr.getPermissionsForRole(self.peon))
+ self.failUnless( [(self.read, Allow)] == l )
+
+ l = list(mgr.getRolesForPermission(self.read))
+ self.failUnless( (self.manager, Allow) in l )
+ self.failUnless( (self.peon, Allow) in l )
+
+ l = list(mgr.getRolesForPermission(self.write))
+ self.assertEqual(l, [ (self.manager, Allow) ] )
+
+ mgr.denyPermissionToRole(self.read, self.peon)
+ l = list(mgr.getPermissionsForRole(self.peon))
+ self.assertEqual(l, [(self.read, Deny)] )
+
+ mgr.unsetPermissionFromRole(self.read, self.peon)
+
+ l = list(mgr.getRolesForPermission(self.read))
+ self.assertEqual(l, [ (self.manager, Allow) ] )
+
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testBasicAuthAdapter.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+import unittest, sys
+
+from Zope.App.Security.BasicAuthAdapter import BasicAuthAdapter
+
+class Request:
+
+ def __init__(self, lpw):
+ self.lpw = lpw
+
+ def _authUserPW(self):
+ return self.lpw
+
+ challenge = None
+ def unauthorized(self, challenge):
+ self.challenge = challenge
+
+
+class Test(unittest.TestCase):
+
+ def testBasicAuthAdapter(self):
+ r = Request(None)
+ a = BasicAuthAdapter(r)
+ self.assertEqual(a.getLogin(), None)
+ self.assertEqual(a.getPassword(), None)
+ r = Request(("tim", "123"))
+ a = BasicAuthAdapter(r)
+ self.assertEqual(a.getLogin(), "tim")
+ self.assertEqual(a.getPassword(), "123")
+
+ def testUnauthorized(self):
+ r = Request(None)
+ a = BasicAuthAdapter(r)
+ a.needLogin("tim")
+ self.assertEqual(r.challenge, "basic realm=tim")
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testLoginPassword.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+import unittest, sys
+
+from Zope.App.Security.LoginPassword import LoginPassword
+
+class Test(unittest.TestCase):
+
+ def testLoginPassword(self):
+ lp = LoginPassword("tim", "123")
+ self.assertEqual(lp.getLogin(), "tim")
+ self.assertEqual(lp.getPassword(), "123")
+ lp = LoginPassword(None, None)
+ self.assertEqual(lp.getLogin(), None)
+ self.assertEqual(lp.getPassword(), None)
+ lp = LoginPassword(None, "123")
+ self.assertEqual(lp.getLogin(), None)
+ self.assertEqual(lp.getPassword(), None)
+ lp = LoginPassword("tim", None)
+ self.assertEqual(lp.getLogin(), "tim")
+ self.assertEqual(lp.getPassword(), "")
+ lp.needLogin("tim") # This method should exist
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testPermissionRegistry.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+""" Test handler for 'definePermission' directive
+
+$Id$
+"""
+
+
+import unittest, sys
+
+from Zope.App.Security.PermissionRegistry import permissionRegistry
+from Zope.App.Security.IPermission import IPermission
+from Interface.Verify import verifyObject
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+
+class Test(CleanUp, unittest.TestCase):
+
+ def testEmptyPermissions(self):
+ self.assertEqual(None, permissionRegistry.getPermission('Foo'))
+ self.failIf(permissionRegistry.definedPermission('Foo'))
+
+ def testPermissionStartsWithDot(self):
+ self.assertRaises(ValueError, permissionRegistry.definePermission,
+ '.Foo', 'dot foo title')
+
+ def testPermissionIsAnIPermission(self):
+ permissionRegistry.definePermission('Foo', 'foo title')
+ permission = permissionRegistry.getPermission('Foo')
+ self.assertEqual(verifyObject(IPermission, permission), 1)
+
+ def testDefinePermission(self):
+ perm = permissionRegistry.definePermission('Foo', 'foo title')
+ self.failUnless(verifyObject(IPermission, perm))
+ self.failUnless(permissionRegistry.definedPermission('Foo'))
+ permission = permissionRegistry.getPermission('Foo')
+ self.assertEquals(permission.getTitle(), 'foo title')
+
+ def testDefinePermissionWithTitle(self):
+ eq = self.assertEqual
+ permissionRegistry.definePermission('Foo', 'Foo-able')
+ permission = permissionRegistry.getPermission('Foo')
+ eq(permission.getTitle(), 'Foo-able')
+ eq(permission.getDescription(), '')
+
+ def testDefinePermissionWithTitleAndDescription(self):
+ eq = self.assertEqual
+ permissionRegistry.definePermission('Foo', 'Foo-able',
+ 'A foo-worthy permission')
+ permission = permissionRegistry.getPermission('Foo')
+ eq(permission.getTitle(), 'Foo-able')
+ eq(permission.getDescription(), 'A foo-worthy permission')
+
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testPrincipalPermissionManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test handler for PrincipalPermissionManager module."""
+
+import sys
+import unittest
+
+from Zope.App.Security.PermissionRegistry \
+ import permissionRegistry as permregistry
+from Zope.App.Security.PrincipalRegistry \
+ import principalRegistry as prinregistry
+from Zope.App.Security.PrincipalPermissionManager \
+ import principalPermissionManager as manager
+from Zope.App.Security.Settings import Allow, Deny, Unset
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+
+class Test(CleanUp, unittest.TestCase):
+
+ def _make_principal(self, id=None, title=None):
+ p = prinregistry.definePrincipal(
+ id or 'APrincipal',
+ title or 'A Principal',
+ login = id or 'APrincipal')
+ return p.getId()
+
+ def testUnboundPrincipalPermission(self):
+ permission = permregistry.definePermission('APerm', 'title').getId()
+ principal = self._make_principal()
+ self.assertEqual(manager.getPrincipalsForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal), [])
+
+ def testPrincipalPermission(self):
+ permission = permregistry.definePermission('APerm', 'title').getId()
+ principal = self._make_principal()
+ # check that an allow permission is saved correctly
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Allow)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Allow)])
+ # check that the allow permission is removed.
+ manager.unsetPermissionForPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal), [])
+ # now put a deny in there, check it's set.
+ manager.denyPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Deny)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Deny)])
+ # test for deny followed by allow . The latter should override.
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Allow)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Allow)])
+ # check that allow followed by allow is just a single allow.
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission),
+ [(principal, Allow)])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal),
+ [(permission, Allow)])
+ # check that two unsets in a row quietly ignores the second one.
+ manager.unsetPermissionForPrincipal(permission, principal)
+ manager.unsetPermissionForPrincipal(permission, principal)
+ self.assertEqual(manager.getPrincipalsForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForPrincipal(principal), [])
+ # check the result of getSetting() when it's empty.
+ self.assertEqual(manager.getSetting(permission, principal), Unset)
+ # check the result of getSetting() when it's allowed.
+ manager.grantPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getSetting(permission, principal), Allow)
+ # check the result of getSetting() when it's denied.
+ manager.denyPermissionToPrincipal(permission, principal)
+ self.assertEqual(manager.getSetting(permission, principal), Deny)
+
+ def testManyPermissionsOnePrincipal(self):
+ perm1 = permregistry.definePermission('Perm One', 'title').getId()
+ perm2 = permregistry.definePermission('Perm Two', 'title').getId()
+ prin1 = self._make_principal()
+ manager.grantPermissionToPrincipal(perm1, prin1)
+ manager.grantPermissionToPrincipal(perm2, prin1)
+ perms = manager.getPermissionsForPrincipal(prin1)
+ self.assertEqual(len(perms), 2)
+ self.failUnless((perm1,Allow) in perms)
+ self.failUnless((perm2,Allow) in perms)
+ manager.denyPermissionToPrincipal(perm2, prin1)
+ perms = manager.getPermissionsForPrincipal(prin1)
+ self.assertEqual(len(perms), 2)
+ self.failUnless((perm1,Allow) in perms)
+ self.failUnless((perm2,Deny) in perms)
+ perms = manager.getPrincipalsAndPermissions()
+ self.failUnless((perm1,prin1,Allow) in perms)
+ self.failUnless((perm2,prin1,Deny) in perms)
+
+ def testManyPrincipalsOnePermission(self):
+ perm1 = permregistry.definePermission('Perm One', 'title').getId()
+ prin1 = self._make_principal()
+ prin2 = self._make_principal('Principal 2', 'Principal Two')
+ manager.grantPermissionToPrincipal(perm1, prin1)
+ manager.denyPermissionToPrincipal(perm1, prin2)
+ principals = manager.getPrincipalsForPermission(perm1)
+ self.assertEqual(len(principals), 2)
+ self.failUnless((prin1,Allow) in principals)
+ self.failUnless((prin2,Deny) in principals)
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testPrincipalPermissionView.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""
+
+$Id$
+"""
+
+import unittest
+
+from Zope.ComponentArchitecture import getService, getServiceManager
+from Zope.App.OFS.Annotation.IAttributeAnnotatable import IAttributeAnnotatable
+from Zope.App.OFS.Annotation.IAnnotations import IAnnotations
+from Zope.App.OFS.Annotation.AttributeAnnotations import AttributeAnnotations
+from Zope.App.Security.IPermissionService import IPermissionService
+from Zope.App.Security.IAuthenticationService import IAuthenticationService
+from Zope.App.Security.IPrincipalPermissionManager \
+ import IPrincipalPermissionManager
+from Zope.App.Security.IPrincipalPermissionMap import IPrincipalPermissionMap
+from Zope.App.Security.Settings import Allow, Deny, Unset
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup \
+ import PlacefulSetup
+
+class DummyContext:
+
+ __implements__ = IAttributeAnnotatable
+#IPrincipalPermissionManager, IPrincipalPermissionMap
+
+class DummyPermissionService:
+
+ __implements__ = IPermissionService
+
+ def __init__(self, perm_objs):
+ perms = {}
+ for perm_obj in perm_objs:
+ perms[perm_obj.getId()] = perm_obj
+
+ self.perms = perms
+
+ def getPermission(self,pr_id):
+ return self.perms[pr_id]
+
+ def getPermissions(self):
+ return self.perms.keys()
+
+
+class DummyAuthenticationService:
+ __implements__ = IAuthenticationService
+
+ def __init__(self, principals):
+ pr = {}
+ for principal in principals:
+ pr[principal.getId()] = principal
+ self.principals = pr
+
+ def getPrincipal(self, principal_id):
+ return self.principals[principal_id]
+
+class DummyAdapter:
+
+ __implements__ = IPrincipalPermissionManager, IPrincipalPermissionMap
+
+ def __init__(self, context):
+ self._context = context
+ if not hasattr(self._context,'principals'):
+ self._context.principals = {}
+
+ def grantPermissionToPrincipal(self, permission, principal):
+ if not (principal in self._context.principals):
+ self._context.principals[principal]={}
+
+ self._context.principals[principal][permission]=Allow
+
+ def denyPermissionToPrincipal(self, permission, principal):
+ if not (principal in self._context.principals):
+ self._context.principals[principal]={}
+
+ self._context.principals[principal][permission]=Deny
+
+ def unsetPermissionForPrincipal(self, permission, principal):
+ if not (principal in self._context.principals):
+ return
+ try:
+ del self._context.principals[principal][permission]
+ except KeyError:
+ pass
+
+ def getSetting(self, permission, principal):
+ try:
+ setting = self._context.principals[principal][permission]
+
+ except KeyError:
+ setting = Unset
+
+ return setting
+
+ def getPrincipalsForPermission(self, permission):
+ ret = []
+ for principal, permissions in self._context.principals.items():
+ if permissions in permissions:
+ ret.append((principal, permissions[permission]))
+ return ret
+
+ def getPermissionsForPrincipal(self, principal):
+ try:
+ return self._context.principals[principal].items()
+ except KeyError:
+ return []
+
+class DummyObject:
+ def __init__(self, id, title):
+ self._id = id
+ self._title = title
+
+ def getId(self):
+ return self._id
+
+ def getTitle(self):
+ return self._title
+
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+ self._permissions = []
+ self._permissions.append(DummyObject('qux', 'Qux'))
+ self._permissions.append(DummyObject('baz', 'Baz'))
+ defineService=getServiceManager(None).defineService
+ provideService=getServiceManager(None).provideService
+
+ defineService(
+ 'PermissionService', IPermissionService)
+ provideService('PermissionService',
+ DummyPermissionService(self._permissions))
+
+ defineService('AuthenticationService',
+ IAuthenticationService)
+
+ self._principals = []
+ self._principals.append(DummyObject('foo', 'Foo'))
+ self._principals.append(DummyObject('bar', 'Bar'))
+
+ provideService('AuthenticationService',
+ DummyAuthenticationService(principals = self._principals))
+ provideAdapter=getService(None,'Adapters').provideAdapter
+ provideAdapter(IAttributeAnnotatable,
+ IPrincipalPermissionManager, DummyAdapter)
+ provideAdapter(
+ IAttributeAnnotatable, IAnnotations, AttributeAnnotations)
+
+ def _makeOne(self):
+ from Zope.App.Security.PrincipalPermissionView \
+ import PrincipalPermissionView
+ return PrincipalPermissionView(DummyContext(), None)
+
+ def testGrantPermissions(self):
+ view = self._makeOne()
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ denied_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Deny')
+
+ self.assertEqual(len(allowed_perms), 0, 'List not empty')
+ self.assertEqual(len(denied_perms), 0, 'List not empty')
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow'),
+ [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny'),
+ [])
+
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[1].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow').sort(),
+ self._permissions.sort())
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny'),
+ [])
+
+ view.grantPermissions(self._principals[1].getId(),
+ [self._permissions[0].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Allow'),
+ [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Deny'),
+ [])
+
+ view.grantPermissions(self._principals[1].getId(),
+ [self._permissions[1].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Allow').sort(),
+ self._permissions.sort())
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Deny'),
+ [])
+
+ def testDenyPermissions(self):
+ view = self._makeOne()
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ denied_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Deny')
+
+ self.assertEqual(len(allowed_perms), 0, 'List not empty')
+ self.assertEqual(len(denied_perms), 0, 'List not empty')
+ view.denyPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny'),
+ [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow'),
+ [])
+
+ view.denyPermissions(self._principals[0].getId(),
+ [self._permissions[1].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny').sort(),
+ self._permissions.sort())
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow'),
+ [])
+
+ view.denyPermissions(self._principals[1].getId(), [
+ self._permissions[0].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Deny'),
+ [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Allow'),
+ [])
+
+ view.denyPermissions(self._principals[1].getId(),
+ [self._permissions[1].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Deny').sort(),
+ self._permissions.sort())
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[1].getId(),'Allow'),
+ [])
+
+ def testAllowDenyPermissions(self):
+ view = self._makeOne()
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ denied_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Deny')
+
+ self.assertEqual(len(allowed_perms), 0, 'List not empty')
+ self.assertEqual(len(denied_perms), 0, 'List not empty')
+
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow'),
+ [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny'),
+ [])
+
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 1, 'List has wrong length')
+
+ # Now change it to deny
+ view.denyPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny'),
+ [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow'),
+ [])
+
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[1].getId()])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Deny'), [self._permissions[0]])
+ self.assertEqual(view.getPermissionsForPrincipal(
+ self._principals[0].getId(),'Allow'), [self._permissions[1]])
+
+ def testUnsetPermissions(self):
+ view = self._makeOne()
+
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 1, 'List has wrong length')
+
+ view.unsetPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 0, 'Permission not unset')
+
+ # Deleting mutiple in one step
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId(),
+ self._permissions[1].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 2, 'List has wrong length')
+
+ view.unsetPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId(),
+ self._permissions[1].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 0, 'Some permissions not unset')
+
+ # Deleting in a row
+ view.grantPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId(),
+ self._permissions[1].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 2, 'List has wrong length')
+
+ view.unsetPermissions(self._principals[0].getId(),
+ [self._permissions[0].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 1, 'Some permissions not unset')
+
+ view.unsetPermissions(self._principals[0].getId(),
+ [self._permissions[1].getId()])
+ allowed_perms = view.getPermissionsForPrincipal(
+ self._principals[0].getId(), 'Allow')
+ self.assertEqual(len(allowed_perms), 0, 'Not all permissions unset')
+
+ # Ask for an other way of getting the unset permisssions
+ unset_perms = view.getUnsetPermissionsForPrincipal(
+ self._principals[0].getId())
+ self.assertEqual(len(unset_perms), 2, 'Not all permissions unset')
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testPrincipalRegistry.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+import unittest, sys
+
+from Zope.App.Security.PrincipalRegistry import PrincipalRegistry
+from Zope.App.Security.PrincipalRegistry import DuplicateLogin, DuplicateId
+from Zope.Exceptions import NotFoundError
+from Zope.Publisher.HTTP.IHTTPCredentials import IHTTPCredentials
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup \
+ import PlacefulSetup
+
+class Request:
+
+ __implements__ = IHTTPCredentials
+
+ def __init__(self, lpw):
+ self.__lpw = lpw
+
+ def _authUserPW(self):
+ return self.__lpw
+
+ challenge = None
+ def unauthorized(self, challenge):
+ self.challenge = challenge
+
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+
+ from Zope.ComponentArchitecture import getService
+ from Zope.App.Security.BasicAuthAdapter import BasicAuthAdapter
+ from Zope.App.Security.ILoginPassword import ILoginPassword
+ getService(None,"Adapters").provideAdapter(
+ IHTTPCredentials, ILoginPassword, BasicAuthAdapter)
+
+ self.reg = PrincipalRegistry()
+
+ self.reg.definePrincipal('1', 'Tim Peters', 'Sir Tim Peters',
+ 'tim', '123')
+ self.reg.definePrincipal('2', 'Jim Fulton', 'Sir Jim Fulton',
+ 'jim', '456')
+
+ def testRegistered(self):
+ p = self.reg.getPrincipal('1')
+ self.assertEqual(p.getId(), '1')
+ self.assertEqual(p.getTitle(), 'Tim Peters')
+ self.assertEqual(p.getDescription(), 'Sir Tim Peters')
+ p = self.reg.getPrincipal('2')
+ self.assertEqual(p.getId(), '2')
+ self.assertEqual(p.getTitle(), 'Jim Fulton')
+ self.assertEqual(p.getDescription(), 'Sir Jim Fulton')
+
+ self.assertEqual(len(self.reg.getPrincipals('')), 2)
+
+ def testUnRegistered(self):
+ self.assertRaises(NotFoundError, self.reg.getPrincipal, '3')
+
+ def testDup(self):
+ self.assertRaises(DuplicateId,
+ self.reg.definePrincipal,
+ '1', 'Tim Peters', 'Sir Tim Peters',
+ 'tim2', '123')
+ self.assertRaises(DuplicateLogin,
+ self.reg.definePrincipal,
+ '3', 'Tim Peters', 'Sir Tim Peters',
+ 'tim', '123')
+ self.assertRaises(NotFoundError, self.reg.getPrincipal, '3')
+ self.assertEqual(len(self.reg.getPrincipals('')), 2)
+
+ def testSearch(self):
+ r = self.reg.getPrincipals('J')
+ self.assertEquals(len(r), 1)
+ self.failUnless(r[0] is self.reg.getPrincipal('2'))
+
+ def testByLogin(self):
+ tim = self.reg.getPrincipalByLogin('tim')
+ self.assertEquals(tim.getLogin(), 'tim')
+ jim = self.reg.getPrincipalByLogin('jim')
+ self.assertEquals(jim.getLogin(), 'jim')
+ self.assertRaises(NotFoundError,
+ self.reg.getPrincipalByLogin, 'kim')
+
+ def testValidation(self):
+ tim = self.reg.getPrincipalByLogin('tim')
+ self.assert_(tim.validate('123'))
+ self.failIf(tim.validate('456'))
+ self.failIf(tim.validate(''))
+ self.failIf(tim.validate('1234'))
+ self.failIf(tim.validate('12'))
+
+ def testAuthenticate(self):
+ req = Request(('tim', '123'))
+ pid = self.reg.authenticate(req)
+ self.assertEquals(pid, '1')
+ req = Request(('tim', '1234'))
+ pid = self.reg.authenticate(req)
+ self.assertEquals(pid, None)
+ req = Request(('kim', '123'))
+ pid = self.reg.authenticate(req)
+ self.assertEquals(pid, None)
+
+ def testUnauthorized(self):
+ request = Request(None)
+ self.reg.unauthorized(self.reg.defaultPrincipal(), request)
+ self.assertEquals(request.challenge, "basic realm=zope")
+ request = Request(None)
+ self.reg.unauthorized(None, request)
+ self.assertEquals(request.challenge, "basic realm=zope")
+ request = Request(None)
+ self.reg.unauthorized("1", request)
+ self.assertEquals(request.challenge, None)
+
+ def testDefaultPrincipal(self):
+ self.assertEquals(self.reg.defaultPrincipal(), None)
+ self.assertRaises(DuplicateId, self.reg.defineDefaultPrincipal,
+ "1", "tim")
+ self.reg.defineDefaultPrincipal("everybody", "Default Principal")
+ self.assertEquals(self.reg.defaultPrincipal(), "everybody")
+ self.reg.defineDefaultPrincipal("anybody", "Default Principal",
+ "This is the default headmaster")
+ self.assertEquals(self.reg.defaultPrincipal(), "anybody")
+ self.assertRaises(NotFoundError, self.reg.getPrincipal, "everybody")
+ p = self.reg.getPrincipal("anybody")
+ self.assertEquals(p.getId(), "anybody")
+ self.assertEquals(p.getTitle(), "Default Principal")
+ self.assertRaises(DuplicateId, self.reg.definePrincipal,
+ "anybody", "title")
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testPrincipalRoleManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test handler for PrincipalRoleManager module."""
+
+import sys
+import unittest
+
+from Zope.App.Security.RoleRegistry import roleRegistry as rregistry
+from Zope.App.Security.PrincipalRegistry import principalRegistry as pregistry
+from Zope.App.Security.PrincipalRoleManager import principalRoleManager
+from Zope.App.Security.Settings import Assign, Remove
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+
+class Test(CleanUp, unittest.TestCase):
+
+ def _make_principal(self, id=None, title=None):
+ p = pregistry.definePrincipal(
+ id or 'APrincipal',
+ title or 'A Principal',
+ login = id or 'APrincipal')
+ return p.getId()
+
+ def testUnboundPrincipalRole(self):
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role), [])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [])
+
+ def testPrincipalRoleAssign(self):
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ principalRoleManager.assignRoleToPrincipal(role, principal)
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role),
+ [(principal,Assign)])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [(role,Assign)])
+
+ def testPrincipalRoleRemove(self):
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ principalRoleManager.removeRoleFromPrincipal(role, principal)
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role),
+ [(principal,Remove)])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [(role,Remove)])
+
+ def testPrincipalRoleUnset(self):
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ principal = self._make_principal()
+ principalRoleManager.removeRoleFromPrincipal(role, principal)
+ principalRoleManager.unsetRoleForPrincipal(role, principal)
+ self.assertEqual(principalRoleManager.getPrincipalsForRole(role),
+ [])
+ self.assertEqual(principalRoleManager.getRolesForPrincipal(principal),
+ [])
+
+ def testManyRolesOnePrincipal(self):
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ role2 = rregistry.defineRole('Role Two', 'Role #2').getId()
+ prin1 = self._make_principal()
+ principalRoleManager.assignRoleToPrincipal(role1, prin1)
+ principalRoleManager.assignRoleToPrincipal(role2, prin1)
+ roles = principalRoleManager.getRolesForPrincipal(prin1)
+ self.assertEqual(len(roles), 2)
+ self.failUnless((role1,Assign) in roles)
+ self.failUnless((role2,Assign) in roles)
+
+ def testManyPrincipalsOneRole(self):
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ prin1 = self._make_principal()
+ prin2 = self._make_principal('Principal 2', 'Principal Two')
+ principalRoleManager.assignRoleToPrincipal(role1, prin1)
+ principalRoleManager.assignRoleToPrincipal(role1, prin2)
+ principals = principalRoleManager.getPrincipalsForRole(role1)
+ self.assertEqual(len(principals), 2)
+ self.failUnless((prin1,Assign) in principals)
+ self.failUnless((prin2,Assign) in principals)
+
+ def testPrincipalsAndRoles(self):
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ role2 = rregistry.defineRole('Role Two', 'Role #2').getId()
+ prin1 = self._make_principal()
+ prin2 = self._make_principal('Principal 2', 'Principal Two')
+ principalRoleManager.assignRoleToPrincipal(role1, prin1)
+ principalRoleManager.assignRoleToPrincipal(role1, prin2)
+ principalRoleManager.assignRoleToPrincipal(role2, prin1)
+ principalsAndRoles = principalRoleManager.getPrincipalsAndRoles()
+ self.assertEqual(len(principalsAndRoles), 3)
+ self.failUnless((role1,prin1,Assign) in principalsAndRoles)
+ self.failUnless((role1,prin2,Assign) in principalsAndRoles)
+ self.failUnless((role2,prin1,Assign) in principalsAndRoles)
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testPrincipalRoleView.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""
+
+$Id$
+"""
+
+import unittest
+
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup\
+ import PlacefulSetup
+from Zope.ComponentArchitecture import getServiceManager
+
+from Zope.App.Security.IRoleService import IRoleService
+from Zope.App.Security.IAuthenticationService import IAuthenticationService
+
+from Zope.App.Security.IPrincipalRoleManager import IPrincipalRoleManager
+from Zope.App.Security.IPrincipalRoleMap import IPrincipalRoleMap
+
+class DummyManager:
+
+ __implements__ = IPrincipalRoleManager
+
+ def getSetting(self, role, principal):
+ return '%r:%r' % (role, principal)
+
+class DummyRoleService:
+
+ __implements__ = IRoleService
+
+ def __init__(self, roles):
+ self._roles = roles
+
+ def getRoles(self):
+ return self._roles
+
+class DummyObject:
+ def __init__(self, id, title):
+ self._id = id
+ self._title = title
+
+ def getId(self):
+ return self._id
+
+ def getTitle(self):
+ return self._title
+
+class DummyAuthenticationService:
+
+ __implements__ = IAuthenticationService
+
+ def __init__(self, principals):
+ self._principals = principals
+
+ def getPrincipals(self):
+ return self._principals
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+ self._roles = []
+ self._roles.append(DummyObject('qux', 'Qux'))
+ self._roles.append(DummyObject('baz', 'Baz'))
+ defineService=getServiceManager(None).defineService
+ provideService=getServiceManager(None).provideService
+
+ defineService('RoleService', IRoleService)
+ provideService('RoleService'
+ , DummyRoleService(roles = self._roles))
+
+ defineService('AuthenticationService', IAuthenticationService)
+
+ self._principals = []
+ self._principals.append(DummyObject('foo', 'Foo'))
+ self._principals.append(DummyObject('bar', 'Bar'))
+
+ provideService('AuthenticationService',
+ DummyAuthenticationService(principals = self._principals))
+
+ def _makeOne(self):
+ from Zope.App.Security.PrincipalRoleView import PrincipalRoleView
+ return PrincipalRoleView(DummyManager(), None)
+
+ def testRoles(self):
+ view = self._makeOne()
+ roles = list(view.getAllRoles())
+ self.assertEqual(len(roles), 2)
+
+ ids = map(lambda x: x.getId(), self._roles)
+ titles = map(lambda x: x.getTitle(), self._roles)
+
+ for role in roles:
+ self.failUnless(role.getId() in ids)
+ self.failUnless(role.getTitle() in titles)
+
+ def testPrincipals(self):
+ view = self._makeOne()
+ principals = list(view.getAllPrincipals())
+ self.assertEqual(len(principals), 2)
+
+ ids = map(lambda x: x.getId(), self._principals)
+ titles = map(lambda x: x.getTitle(), self._principals)
+
+ for principal in principals:
+ self.failUnless(principal.getId() in ids)
+ self.failUnless(principal.getTitle() in titles)
+
+ def testPrincipalRoleGrid(self):
+ view = self._makeOne()
+
+ grid = view.createGrid()
+
+ p_ids = [p.getId() for p in view.getAllPrincipals()]
+ r_ids = [r.getId() for r in view.getAllRoles()]
+
+ self.failUnless(grid.listAvailableValues())
+
+ for id in [p.getId() for p in grid.principals()]:
+ self.failUnless(id in p_ids)
+
+ for id in [r.getId() for r in grid.roles()]:
+ self.failUnless(id in r_ids)
+
+ map = DummyManager()
+
+ grid_entries = [(r, p, map.getSetting(r, p))
+ for r in grid.roles()
+ for p in grid.principals()]
+
+ for r, p, setting in grid_entries:
+ self.assertEquals(setting, grid.getValue(r, p))
+
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testProtectClass.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+""" Test handler for 'protectClass' directive """
+
+import unittest
+
+from TestModuleHookup import *
+from Zope.App.Security.PermissionRegistry import permissionRegistry
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+from Zope.App.Security.protectClass import protectName, protectLikeUnto
+
+NOTSET = []
+
+P1 = "extravagant"
+P2 = "paltry"
+
+class Test(CleanUp, unittest.TestCase):
+
+ def setUp(self):
+ permissionRegistry.definePermission(P1, P1)
+ permissionRegistry.definePermission(P2, P2)
+
+ class B:
+ def m1(self):
+ return "m1"
+ def m2(self):
+ return "m2"
+ class C(B):
+ __implements__ = I
+ def m3(self):
+ return "m3"
+ def m4(self):
+ return "m4"
+ TestModule.test_base = B
+ TestModule.test_class = C
+ TestModule.test_instance = C()
+ self.assertState()
+
+ def tearDown(self):
+ CleanUp.tearDown(self)
+ TestModule.test_class = None
+
+ def assertState(self, instP=NOTSET,
+ m1P=NOTSET, m2P=NOTSET, m3P=NOTSET):
+ "Verify that class, instance, and methods have expected permissions."
+
+ from Zope.Security.Checker import selectChecker
+ from Zope.Exceptions import Forbidden
+
+ checker = selectChecker(TestModule.test_instance)
+ self.assertEqual(checker.permission_id('m1'), (m1P or None))
+ self.assertEqual(checker.permission_id('m2'), (m2P or None))
+ self.assertEqual(checker.permission_id('m3'), (m3P or None))
+
+ # "testSimple*" exercises tags that do NOT have children. This mode
+ # inherently sets the instances as well as the class attributes.
+
+ def testSimpleMethodsPlural(self):
+ protectName(TestModule.test_class, 'm1', P1)
+ protectName(TestModule.test_class, 'm3', P1)
+ self.assertState(instP=P1, m1P=P1, m3P=P1)
+
+ def testLikeUntoOnly(self):
+ protectName(TestModule.test_base, 'm1', P1)
+ protectName(TestModule.test_base, 'm2', P1)
+ protectLikeUnto(TestModule.test_class, TestModule.test_base)
+ # m1 and m2 are in the interface, so should be set, and m3 should not:
+ self.assertState(m1P=P1, m2P=P1)
+
+
+ def testLikeUntoAsDefault(self):
+ protectName(TestModule.test_base, 'm1', P1)
+ protectName(TestModule.test_base, 'm2', P1)
+ protectLikeUnto(TestModule.test_class, TestModule.test_base)
+ protectName(TestModule.test_class, 'm2', P2)
+ protectName(TestModule.test_class, 'm3', P2)
+ # m1 and m2 are in the interface, so should be set, and m3 should not:
+ self.assertState(m1P=P1, m2P=P2, m3P=P2)
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testProtectSubClass.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test proper protection of inherited methods
+
+Revision information:
+$Id$
+"""
+
+from unittest import TestCase, TestSuite, main, makeSuite
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+from Zope.App.Security.protectClass import protectName
+from Zope.App.Security.PermissionRegistry import permissionRegistry
+from Zope.Security.Checker import selectChecker
+
+class Test(CleanUp, TestCase):
+
+ def testInherited(self):
+
+ class B1(object):
+ def g(self): return 'B1.g'
+
+ class B2(object):
+ def h(self): return 'B2.h'
+
+ class S(B1, B2):
+ pass
+
+ permissionRegistry.definePermission('B1', '')
+ permissionRegistry.definePermission('S', '')
+ protectName(B1, 'g', 'B1')
+ protectName(S, 'g', 'S')
+ protectName(S, 'h', 'S')
+
+ self.assertEqual(selectChecker(B1()).permission_id('g'), 'B1')
+ self.assertEqual(selectChecker(B2()).permission_id('h'), None)
+ self.assertEqual(selectChecker(S()).permission_id('g'), 'S')
+ self.assertEqual(selectChecker(S()).permission_id('h'), 'S')
+
+ self.assertEqual(S().g(), 'B1.g')
+ self.assertEqual(S().h(), 'B2.h')
+
+
+def test_suite():
+ return TestSuite((
+ makeSuite(Test),
+ ))
+
+if __name__=='__main__':
+ main(defaultTest='test_suite')
=== Zope3/lib/python/Zope/App/Security/tests/testRolePermissionManager.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Test handler for RolePermissionManager module."""
+
+import sys
+import unittest
+
+from Zope.App.Security.PermissionRegistry \
+ import permissionRegistry as pregistry
+from Zope.App.Security.RoleRegistry \
+ import roleRegistry as rregistry
+from Zope.App.Security.RolePermissionManager \
+ import rolePermissionManager as manager
+from Zope.App.Security.Settings \
+ import Allow, Deny, Unset
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+
+class Test(CleanUp, unittest.TestCase):
+
+ def testUnboundRolePermission(self):
+ permission = pregistry.definePermission('APerm', 'aPerm title').getId()
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ self.assertEqual(manager.getRolesForPermission(permission), [])
+ self.assertEqual(manager.getPermissionsForRole(role), [])
+
+ def testRolePermission(self):
+ permission = pregistry.definePermission('APerm', 'aPerm title').getId()
+ role = rregistry.defineRole('ARole', 'A Role').getId()
+ manager.grantPermissionToRole(permission, role)
+ self.assertEqual(manager.getRolesForPermission(permission),
+ [(role,Allow)])
+ self.assertEqual(manager.getPermissionsForRole(role),
+ [(permission,Allow)])
+
+ def testManyPermissionsOneRole(self):
+ perm1 = pregistry.definePermission('Perm One', 'P1').getId()
+ perm2 = pregistry.definePermission('Perm Two', 'P2').getId()
+ perm3 = pregistry.definePermission('Perm Three', 'P3').getId()
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ perms = manager.getPermissionsForRole(role1)
+ self.assertEqual(len(perms), 0)
+ manager.grantPermissionToRole(perm1, role1)
+ manager.grantPermissionToRole(perm2, role1)
+ manager.grantPermissionToRole(perm2, role1)
+ manager.denyPermissionToRole(perm3, role1)
+ perms = manager.getPermissionsForRole(role1)
+ self.assertEqual(len(perms), 3)
+ self.failUnless((perm1,Allow) in perms)
+ self.failUnless((perm2,Allow) in perms)
+ self.failUnless((perm3,Deny) in perms)
+ manager.unsetPermissionFromRole(perm1, role1)
+ perms = manager.getPermissionsForRole(role1)
+ self.assertEqual(len(perms), 2)
+ self.failUnless((perm2,Allow) in perms)
+
+ def testManyRolesOnePermission(self):
+ perm1 = pregistry.definePermission('Perm One', 'title').getId()
+ role1 = rregistry.defineRole('Role One', 'Role #1').getId()
+ role2 = rregistry.defineRole('Role Two', 'Role #2').getId()
+ roles = manager.getRolesForPermission(perm1)
+ self.assertEqual(len(roles), 0)
+ manager.grantPermissionToRole(perm1, role1)
+ manager.grantPermissionToRole(perm1, role2)
+ manager.grantPermissionToRole(perm1, role2)
+ manager.denyPermissionToRole(perm1, role1)
+ roles = manager.getRolesForPermission(perm1)
+ self.assertEqual(len(roles), 2)
+ self.failIf((role1,Allow) in roles)
+ self.failUnless((role1,Deny) in roles)
+ self.failUnless((role2,Allow) in roles)
+ manager.unsetPermissionFromRole(perm1, role1)
+ roles = manager.getRolesForPermission(perm1)
+ self.assertEqual(len(roles), 1)
+ self.failUnless((role2,Allow) in roles)
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testRolePermissionView.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+import unittest, sys
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup\
+ import PlacefulSetup
+from Zope.ComponentArchitecture import getServiceManager
+from Zope.App.Security.IRoleService import IRoleService
+from RoleService import RoleService
+from PermissionService import PermissionService
+from RolePermissionManager import RolePermissionManager
+from Zope.App.Security.RolePermissionView import RolePermissionView
+from Zope.App.Security.IPermissionService import IPermissionService
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+ defineService=getServiceManager(None).defineService
+ provideService=getServiceManager(None).provideService
+ defineService('RoleService', IRoleService)
+ provideService('RoleService', RoleService(
+ manager='Manager', member='Member'))
+ defineService('PermissionService', IPermissionService)
+ provideService('PermissionService', PermissionService(
+ read='Read', write='Write'))
+ self.view = RolePermissionView(RolePermissionManager(), None)
+
+ def testRoles(self):
+ roles = list(self.view.roles())
+ ids = ['manager', 'member']
+ titles = ['Manager', 'Member']
+ for role in roles:
+ i=ids.index(role.getId())
+ self.failIf(i < 0)
+ self.assertEqual(role.getTitle(), titles[i])
+ del ids[i]
+ del titles[i]
+
+ def testPermisssions(self):
+ permissions = list(self.view.permissions())
+ ids = ['read', 'write']
+ titles = ['Read', 'Write']
+ for permission in permissions:
+ i=ids.index(permission.getId())
+ self.failIf(i < 0)
+ self.assertEqual(permission.getTitle(), titles[i])
+ del ids[i]
+ del titles[i]
+
+ def testGrant(self):
+ roles = self.view.roles()
+ permissions = self.view.permissions()
+
+ self.view.action({
+ 'p0': 'read', 'p1': 'write',
+ 'r0': 'manager', 'r1': 'member',
+ 'p0r0': '1', 'p0r1': '1', 'p1r0': '1',
+ },
+ testing=1)
+ permissionRoles = self.view.permissionRoles()
+ for ip in range(len(permissionRoles)):
+ permissionRole = permissionRoles[ip]
+ rset = permissionRole.roles()
+ for ir in range(len(rset)):
+ setting = rset[ir]
+ if setting is None:
+ self.failIf(
+ roles[ir].getId() == 'manager'
+ or
+ permissions[ip].getId() == 'read'
+ )
+ else:
+ self.failUnless(
+ roles[ir].getId() == 'manager'
+ or
+ permissions[ip].getId() == 'read'
+ )
+
+ self.view.action({
+ 'p0': 'read', 'p1': 'write',
+ 'r0': 'manager', 'r1': 'member',
+ 'p0r0': '1',
+ },
+ testing=1)
+ permissionRoles = self.view.permissionRoles()
+ for ip in range(len(permissionRoles)):
+ permissionRole = permissionRoles[ip]
+ rset = permissionRole.roles()
+ for ir in range(len(rset)):
+ setting = rset[ir]
+ if setting is None:
+ self.failIf(
+ roles[ir].getId() == 'manager'
+ and
+ permissions[ip].getId() == 'read'
+ )
+ else:
+ self.failUnless(
+ roles[ir].getId() == 'manager'
+ and
+ permissions[ip].getId() == 'read'
+ )
+
+
+ self.view.update_permission(REQUEST=None,
+ permission_id='write',
+ roles=['member'],
+ testing=1)
+
+ permission = self.view.permissionForID('write')
+ self.assertEquals(
+ [r['id']
+ for r in permission.rolesInfo()
+ if r['checked']],
+ ['member'])
+
+ self.view.update_permission(REQUEST=None,
+ permission_id='write',
+ # roles=[], roles attr omitted
+ testing=1)
+
+ permission = self.view.permissionForID('write')
+ self.assertEquals(
+ [r['id']
+ for r in permission.rolesInfo()
+ if r['checked']],
+ [])
+
+
+ self.view.update_permission(REQUEST=None,
+ permission_id='write',
+ roles=['manager','member'],
+ testing=1)
+
+ permission = self.view.permissionForID('write')
+ result = [r['id']
+ for r in permission.rolesInfo()
+ if r['checked']]
+ what_result_should_be = ['manager','member']
+ result.sort()
+ what_result_should_be.sort()
+ self.assertEquals(
+ result,
+ what_result_should_be
+ )
+
+ self.view.update_role(REQUEST=None,
+ role_id='member',
+ permissions=['write','read'],
+ testing=1)
+
+ role = self.view.roleForID('member')
+ result = [r['id']
+ for r in role.permissionsInfo()
+ if r['checked']]
+ what_result_should_be = ['write','read']
+ result.sort()
+ what_result_should_be.sort()
+ self.assertEquals(
+ result,
+ what_result_should_be
+ )
+
+ self.view.update_role(REQUEST=None,
+ role_id='member',
+ # omitted attribute permissions,
+ testing=1)
+
+ role = self.view.roleForID('member')
+ result = [r['id']
+ for r in role.permissionsInfo()
+ if r['checked']]
+ what_result_should_be = []
+ result.sort()
+ what_result_should_be.sort()
+ self.assertEquals(
+ result,
+ what_result_should_be
+ )
+
+
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testRoleRegistry.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+""" Test handler for 'defineRole' directive """
+
+import unittest, sys
+
+from Zope.App.Security.RoleRegistry import roleRegistry
+from Zope.App.Security.IRole import IRole
+from Interface.Verify import verifyObject
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+
+class Test(CleanUp, unittest.TestCase):
+
+ def testEmptyRoles(self):
+ self.assertEqual(None, roleRegistry.getRole('Foo'))
+ self.failIf(roleRegistry.definedRole('Foo'))
+
+ def testRoleIsAnIRole(self):
+ r = roleRegistry.defineRole('Foo', 'Foo role')
+ role = roleRegistry.getRole(r.getId())
+ self.assertEqual(verifyObject(IRole, role), 1)
+
+ def testDefineRole(self):
+ role = roleRegistry.defineRole('Foo', 'foo role')
+ self.failUnless(verifyObject(IRole, role))
+ self.failUnless(roleRegistry.definedRole(role.getId()))
+ role = roleRegistry.getRole(role.getId())
+ self.assertEquals(role.getTitle(), 'foo role')
+
+ def testDefineRoleWithTitle(self):
+ eq = self.assertEqual
+ r = roleRegistry.defineRole('Foo', 'Foo-able')
+ role = roleRegistry.getRole(r.getId())
+ eq(role.getTitle(), 'Foo-able')
+ eq(role.getDescription(), '')
+
+ def testDefineRoleWithTitleAndDescription(self):
+ eq = self.assertEqual
+ r = roleRegistry.defineRole('Foo', 'Foo-able', 'A foo-worthy role')
+ role = roleRegistry.getRole(r.getId())
+ eq(role.getTitle(), 'Foo-able')
+ eq(role.getDescription(), 'A foo-worthy role')
+
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testSecurityDirectives.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""
+
+$Id$
+"""
+
+import unittest, sys, os
+
+from Zope.Configuration.xmlconfig import xmlconfig
+from StringIO import StringIO
+from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
+from Zope.Configuration.xmlconfig import ZopeXMLConfigurationError
+from Zope.App.Security.PrincipalRegistry import principalRegistry
+from Zope.App.Security.PermissionRegistry \
+ import permissionRegistry as pregistry
+from Zope.App.Security.RoleRegistry import roleRegistry as rregistry
+from Zope.App.Security.RolePermissionManager \
+ import rolePermissionManager as role_perm_mgr
+from Zope.App.Security.PrincipalPermissionManager \
+ import principalPermissionManager as principal_perm_mgr
+from Zope.App.Security.PrincipalRoleManager \
+ import principalRoleManager as principal_role_mgr
+from Zope.App.Security.Settings import Allow, Deny, Unset, Remove, Assign
+
+
+import Zope.App.Security
+defs_path = os.path.join(
+ os.path.split(Zope.App.Security.__file__)[0],
+ 'security-meta.zcml')
+
+def configfile(s):
+ return StringIO("""<zopeConfigure
+ xmlns='http://namespaces.zope.org/zope'
+ xmlns:security='http://namespaces.zope.org/security'>
+ %s
+ </zopeConfigure>
+ """ % s)
+
+class TestPrincipalDirective(CleanUp, unittest.TestCase):
+ def setUp(self):
+ xmlconfig(open(defs_path))
+
+ def testRegister(self):
+ f = configfile("""<security:principal id="1"
+ title="Sir Tim Peters"
+ description="Tim Peters"
+ login="tim" password="123" />
+ <security:principal id="2"
+ title="Sir Jim Fulton"
+ description="Jim Fulton"
+ login="jim" password="123" />""")
+ xmlconfig(f)
+
+ reg=principalRegistry
+
+ p = reg.getPrincipal('1')
+ self.assertEqual(p.getId(), '1')
+ self.assertEqual(p.getTitle(), 'Sir Tim Peters')
+ self.assertEqual(p.getDescription(), 'Tim Peters')
+ p = reg.getPrincipal('2')
+ self.assertEqual(p.getId(), '2')
+ self.assertEqual(p.getTitle(), 'Sir Jim Fulton')
+ self.assertEqual(p.getDescription(), 'Jim Fulton')
+
+ self.assertEqual(len(reg.getPrincipals('')), 2)
+
+
+class TestPermissionDirective(CleanUp, unittest.TestCase):
+ def setUp(self):
+ xmlconfig(open(defs_path))
+
+ def testRegister(self):
+ f = configfile("""
+ <security:permission
+ id="Can Do It"
+ title="A Permissive Permission"
+ description="This permission lets you do anything" />""")
+
+ xmlconfig(f)
+
+ perm = pregistry.getPermission("Can Do It")
+ self.failUnless(perm.getId().endswith('Can Do It'))
+ self.assertEqual(perm.getTitle(), 'A Permissive Permission')
+ self.assertEqual(perm.getDescription(),
+ 'This permission lets you do anything')
+
+ def testDuplicationRegistration(self):
+ f = configfile("""
+ <security:permission
+ id="Can Do It"
+ title="A Permissive Permission"
+ description="This permission lets you do anything" />
+
+ <security:permission
+ id="Can Do It"
+ title="A Permissive Permission"
+ description="This permission lets you do anything" />
+ """)
+
+ #self.assertRaises(AlreadyRegisteredError, xmlconfig, f)
+ self.assertRaises(ZopeXMLConfigurationError, xmlconfig, f)
+
+class TestRoleDirective(CleanUp, unittest.TestCase):
+ def setUp(self):
+ xmlconfig(open(defs_path))
+
+ def testRegister(self):
+ f = configfile("""
+ <security:role
+ id="Everyperson"
+ title="Tout le monde"
+ description="The common man, woman, person, or thing" />
+ """)
+
+ xmlconfig(f)
+
+ role = rregistry.getRole("Everyperson")
+ self.failUnless(role.getId().endswith('Everyperson'))
+ self.assertEqual(role.getTitle(), 'Tout le monde')
+ self.assertEqual(role.getDescription(),
+ 'The common man, woman, person, or thing')
+
+ def testDuplicationRegistration(self):
+ f = configfile("""
+ <security:role
+ id="Everyperson"
+ title="Tout le monde"
+ description="The common man, woman, person, or thing" />
+
+ <security:role
+ id="Everyperson"
+ title="Tout le monde"
+ description="The common man, woman, person, or thing" />
+ """)
+
+ #self.assertRaises(AlreadyRegisteredError, xmlconfig, f)
+ self.assertRaises(ZopeXMLConfigurationError, xmlconfig, f)
+
+class TestRolePermission(CleanUp, unittest.TestCase):
+
+ def setUp( self ):
+ xmlconfig(open(defs_path))
+
+ def testMap( self ):
+ f = configfile("""
+ <security:grantPermissionToRole
+ permission="Foo"
+ role="Bar" />
+ """)
+
+ xmlconfig(f)
+
+ roles = role_perm_mgr.getRolesForPermission("Foo")
+ perms = role_perm_mgr.getPermissionsForRole("Bar")
+
+ self.assertEqual(len( roles ), 1)
+ self.failUnless(("Bar",Allow) in roles)
+
+ self.assertEqual(len( perms ), 1)
+ self.failUnless(("Foo",Allow) in perms)
+
+class TestPrincipalPermission(CleanUp, unittest.TestCase):
+
+ def setUp( self ):
+ xmlconfig(open(defs_path))
+
+ def testMap( self ):
+ f = configfile("""
+ <security:grantPermissionToPrincipal
+ permission="Foo"
+ principal="Bar" />
+ """)
+
+ xmlconfig(f)
+
+ principals = principal_perm_mgr.getPrincipalsForPermission("Foo")
+ perms = principal_perm_mgr.getPermissionsForPrincipal("Bar")
+
+ self.assertEqual(len( principals ), 1)
+ self.failUnless(("Bar", Allow) in principals)
+
+ self.assertEqual(len( perms ), 1)
+ self.failUnless(("Foo", Allow) in perms)
+
+class TestPrincipalRole(CleanUp, unittest.TestCase):
+
+ def setUp( self ):
+ xmlconfig(open(defs_path))
+
+ def testMap( self ):
+ f = configfile("""
+ <security:assignRoleToPrincipal
+ role="Foo"
+ principal="Bar" />
+ """)
+
+ xmlconfig(f)
+
+ principals = principal_role_mgr.getPrincipalsForRole("Foo")
+ roles = principal_role_mgr.getRolesForPrincipal("Bar")
+
+ self.assertEqual(len( principals ), 1)
+ self.failUnless(("Bar",Assign) in principals)
+
+ self.assertEqual(len( roles ), 1)
+ self.failUnless(("Foo",Assign) in roles)
+
+def test_suite():
+ suite = unittest.TestSuite()
+ loader = unittest.TestLoader()
+ suite.addTest(loader.loadTestsFromTestCase(TestPrincipalDirective))
+ suite.addTest(loader.loadTestsFromTestCase(TestPermissionDirective))
+ suite.addTest(loader.loadTestsFromTestCase(TestRoleDirective))
+ suite.addTest(loader.loadTestsFromTestCase(TestRolePermission))
+ suite.addTest(loader.loadTestsFromTestCase(TestPrincipalPermission))
+ suite.addTest(loader.loadTestsFromTestCase(TestPrincipalRole))
+ return suite
+
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testSettings.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+import unittest, sys
+
+from Zope.App.Security.Settings import Allow
+from cPickle import Pickler, Unpickler
+from StringIO import StringIO
+
+class Test(unittest.TestCase):
+
+ def testPickleUnpickle(self):
+ s = StringIO()
+ p = Pickler(s)
+ p.dump(Allow)
+ s.seek(0)
+ u = Unpickler(s)
+ newAllow = u.load()
+
+ self.failUnless(newAllow is Allow)
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())
=== Zope3/lib/python/Zope/App/Security/tests/testZSP.py 1.1 => 1.2 ===
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""
+
+
+Revision information: $Id$
+"""
+
+
+import unittest
+
+from Interface import Interface
+from Zope.Proxy.ContextWrapper import ContextWrapper
+from Zope.ComponentArchitecture import getService
+from Zope.App.Security.IRolePermissionManager import IRolePermissionManager
+from Zope.App.Security.PermissionRegistry import permissionRegistry
+from Zope.App.Security.PrincipalRegistry import principalRegistry
+from Zope.App.Security.RoleRegistry import roleRegistry
+from Zope.App.Security.PrincipalPermissionManager \
+ import principalPermissionManager
+from Zope.App.Security.RolePermissionManager import rolePermissionManager
+from Zope.App.Security.PrincipalRoleManager import principalRoleManager
+from Zope.App.Security.AnnotationPrincipalPermissionManager \
+ import AnnotationPrincipalPermissionManager
+from Zope.App.Security.PrincipalPermissionManager \
+ import PrincipalPermissionManager
+from Zope.App.Security.IPrincipalPermissionManager \
+ import IPrincipalPermissionManager
+from Zope.App.Security.AnnotationPrincipalRoleManager \
+ import AnnotationPrincipalRoleManager
+from Zope.App.Security.PrincipalRoleManager \
+ import PrincipalRoleManager
+from Zope.App.Security.AnnotationRolePermissionManager \
+ import AnnotationRolePermissionManager
+from Zope.App.Security.IPrincipalRoleManager import IPrincipalRoleManager
+from Zope.Exceptions import Unauthorized, Forbidden
+from Zope.App.OFS.Annotation.IAttributeAnnotatable import IAttributeAnnotatable
+from Zope.App.OFS.Annotation.IAnnotations import IAnnotations
+from Zope.App.OFS.Annotation.AttributeAnnotations import AttributeAnnotations
+from Zope.App.OFS.Services.ServiceManager.tests.PlacefulSetup\
+ import PlacefulSetup
+
+class Context:
+ def __init__(self, user, stack=[]):
+ self.user, self.stack = user, stack
+
+class Unprotected:
+ pass
+
+
+
+class Test(PlacefulSetup, unittest.TestCase):
+
+ def setUp(self):
+ PlacefulSetup.setUp(self)
+ getService(None,"Adapters").provideAdapter(
+ IAttributeAnnotatable, IAnnotations,
+ AttributeAnnotations)
+ jim = principalRegistry.definePrincipal('jim', 'Jim', 'Jim Fulton',
+ 'jim', '123')
+ self.jim = jim.getId()
+
+ tim = principalRegistry.definePrincipal('tim', 'Tim', 'Tim Peters',
+ 'tim', '456')
+ self.tim = tim.getId()
+
+ unknown = principalRegistry.defineDefaultPrincipal(
+ 'unknown', 'Unknown', 'Nothing is known about this principal')
+ self.unknown = unknown.getId()
+
+ read = permissionRegistry.definePermission(
+ 'read', 'Read', 'Read something')
+ self.read = read.getId()
+ write = permissionRegistry.definePermission(
+ 'write', 'Write', 'Write something')
+ self.write = write.getId()
+
+ peon = roleRegistry.defineRole('Peon', 'Site Peon')
+ self.peon = peon.getId()
+
+ manager = roleRegistry.defineRole('Manager', 'Site Manager')
+ self.manager = manager.getId()
+
+ arole = roleRegistry.defineRole('Another', 'Another Role')
+ self.arole = arole.getId()
+
+ rolePermissionManager.grantPermissionToRole(self.read, self.peon)
+
+ rolePermissionManager.grantPermissionToRole(self.read, self.manager)
+ rolePermissionManager.grantPermissionToRole(self.write, self.manager)
+
+ principalRoleManager.assignRoleToPrincipal(self.peon, self.jim)
+ principalRoleManager.assignRoleToPrincipal(self.manager, self.tim)
+
+ self.policy = self._makePolicy()
+
+ def _makePolicy( self ):
+
+ from Zope.App.Security.ZopeSecurityPolicy import ZopeSecurityPolicy
+ return ZopeSecurityPolicy()
+
+ def testImport( self ):
+
+ from Zope.App.Security.ZopeSecurityPolicy import ZopeSecurityPolicy
+
+ def testGlobalCheckPermission(self):
+ self.failUnless(
+ self.policy.checkPermission(self.read, None, Context(self.jim)))
+ self.failUnless(
+ self.policy.checkPermission(self.read, None, Context(self.tim)))
+ self.failUnless(
+ self.policy.checkPermission(self.write, None, Context(self.tim)))
+
+ self.failIf(self.policy.checkPermission(
+ self.read, None, Context(self.unknown)))
+ self.failIf(self.policy.checkPermission(
+ self.write, None, Context(self.unknown)))
+
+ self.failIf(
+ self.policy.checkPermission(
+ self.read, None, Context(self.unknown)))
+
+ rolePermissionManager.grantPermissionToRole(self.read, 'Anonymous')
+
+ self.failUnless(
+ self.policy.checkPermission(
+ self.read, None, Context(self.unknown)))
+
+ principalPermissionManager.grantPermissionToPrincipal(
+ self.write, self.jim)
+ self.failUnless(
+ self.policy.checkPermission(self.write, None, Context(self.jim)))
+
+ def testPlayfulRolePermissions(self):
+
+ ARPM = AnnotationRolePermissionManager
+ getService(None,"Adapters").provideAdapter(ITest,
+ IRolePermissionManager, ARPM)
+ test = permissionRegistry.definePermission('test', 'Test', '')
+ test = test.getId()
+
+ ob1 = TestClass()
+ ob2 = TestClass()
+ ob3 = TestClass()
+
+ ob = ContextWrapper(ob3, ContextWrapper(ob2, ob1))
+
+ self.failIf(self.policy.checkPermission(test, ob, Context(self.tim)))
+ ARPM(ob2).grantPermissionToRole(test, self.manager)
+ self.failUnless(self.policy.checkPermission(test, ob,
+ Context(self.tim)))
+
+ self.failIf(self.policy.checkPermission(test, ob, Context(self.jim)))
+ ARPM(ob3).grantPermissionToRole(test, self.peon)
+ self.failUnless(self.policy.checkPermission(
+ test, ob, Context(self.jim)))
+ # Make sure global principal permissions override placeful role perms
+ principalPermissionManager.denyPermissionToPrincipal(
+ test, self.jim)
+ self.failIf(self.policy.checkPermission(
+ test, ob, Context(self.jim)))
+ principalPermissionManager.unsetPermissionForPrincipal(
+ test, self.jim)
+ # Make sure multiple conflicting role permissions resolve correctly
+ ARPM(ob2).grantPermissionToRole(test, 'Anonymous')
+ ARPM(ob2).grantPermissionToRole(test, self.arole)
+ ARPM(ob3).denyPermissionToRole(test, self.peon)
+
+ new = principalRegistry.definePrincipal('new', 'Newbie',
+ 'Newbie User', 'new', '098')
+ new = new.getId()
+ principalRoleManager.assignRoleToPrincipal(self.arole, new)
+ self.failUnless(self.policy.checkPermission(test, ob, Context(new)))
+ principalRoleManager.assignRoleToPrincipal(self.peon, new)
+ self.failIf(self.policy.checkPermission(test, ob, Context(new)))
+
+ def testPlayfulPrinciplePermissions(self):
+ APPM = AnnotationPrincipalPermissionManager
+ getService(None,"Adapters").provideAdapter(ITest,
+ IPrincipalPermissionManager, APPM)
+
+ ob1 = TestClass()
+ ob2 = TestClass()
+ ob3 = TestClass()
+
+ test = permissionRegistry.definePermission('test', 'Test', '')
+ test = test.getId()
+
+ ob = ContextWrapper(ob3, ContextWrapper(ob2, ob1))
+ self.failIf(self.policy.checkPermission(test, ob, Context(self.tim)))
+ APPM(ob2).grantPermissionToPrincipal(test, self.tim)
+ self.failUnless(self.policy.checkPermission(test, ob,
+ Context(self.tim)))
+ APPM(ob3).denyPermissionToPrincipal(test, self.tim)
+ self.failIf(self.policy.checkPermission(test, ob,
+ Context(self.tim)))
+ APPM(ob1).denyPermissionToPrincipal(test, self.jim)
+ APPM(ob3).grantPermissionToPrincipal(test, self.jim)
+ self.failUnless(self.policy.checkPermission(test, ob,
+ Context(self.jim)))
+ APPM(ob3).unsetPermissionForPrincipal(test, self.jim)
+ self.failIf(self.policy.checkPermission(test, ob,
+ Context(self.jim)))
+ # make sure placeful principal permissions override global ones
+ APPM(ob).grantPermissionToPrincipal(test, self.tim)
+ principalPermissionManager.denyPermissionToPrincipal(
+ test, self.tim)
+ self.failUnless(self.policy.checkPermission(test, ob,
+ Context(self.tim)))
+ principalPermissionManager.unsetPermissionForPrincipal(
+ test, self.tim)
+
+
+class ITest(IAttributeAnnotatable):
+ pass
+
+class TestClass:
+ __implements__ = ITest
+
+ def __init__(self):
+ self._roles = { 'test' : {} }
+ self._permissions = { 'Manager' : {} , 'Peon' : {} }
+
+def test_suite():
+ loader=unittest.TestLoader()
+ return loader.loadTestsFromTestCase(Test)
+
+if __name__=='__main__':
+ unittest.TextTestRunner().run(test_suite())