[Zope-Checkins] CVS: Zope3/lib/python/Zope/App/Security/Management/tests - RolePermissionsManager.py:1.1.2.1 __init__.py:1.1.2.1 testGlobalPrincipalPermissions.py:1.1.2.1 testGlobalPrincipalRoles.py:1.1.2.1 testGlobalRolePermissions.py:1.1.2.1 testMementoPrincipalPermissions.py:1.1.2.1 testMementoPrincipalRoles.py:1.1.2.1 testMementoRolePermissions.py:1.1.2.1 testPrincipalPermissionsView.py:1.1.2.1 testPrincipalRolesView.py:1.1.2.1 testRolePermissionsView.py:1.1.2.1 testSettings.py:1.1.2.1

Casey Duncan casey@zope.com
Tue, 9 Apr 2002 12:36:45 -0400


Update of /cvs-repository/Zope3/lib/python/Zope/App/Security/Management/tests
In directory cvs.zope.org:/tmp/cvs-serv11768/Zope/App/Security/Management/tests

Added Files:
      Tag: casey-security-reorg-branch
	RolePermissionsManager.py __init__.py 
	testGlobalPrincipalPermissions.py testGlobalPrincipalRoles.py 
	testGlobalRolePermissions.py 
	testMementoPrincipalPermissions.py 
	testMementoPrincipalRoles.py testMementoRolePermissions.py 
	testPrincipalPermissionsView.py testPrincipalRolesView.py 
	testRolePermissionsView.py testSettings.py 
Log Message:
Mass checkin for security reorganization branch. I will retest this and merge
upon BDFL approval...


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/RolePermissionsManager.py ===
##############################################################################
#
# Copyright (c) 2001 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: RolePermissionsManager.py,v 1.1.2.1 2002/04/09 16:36:43 caseman Exp $
"""

from Zope.App.Security.Management.IRolePermissions \
     import IRolePermissionsManager
from Zope.App.Security.Management.Settings import Allow, Assign

class RolePermissionsManager:

    __implements__ = IRolePermissionsManager

    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]



=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/__init__.py ===



=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testGlobalPrincipalPermissions.py ===
# Copyright (c) 2001 Zope Coporation and Contributors.  All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (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: testGlobalPrincipalPermissions.py,v 1.1.2.1 2002/04/09 16:36:43 caseman Exp $
"""

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.Management.GlobalPrincipalPermissions \
     import principalPermissionsManager as manager
from Zope.App.Security.Management.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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testGlobalPrincipalRoles.py ===
# Copyright (c) 2001 Zope Coporation and Contributors.  All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (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: testGlobalPrincipalRoles.py,v 1.1.2.1 2002/04/09 16:36:43 caseman Exp $
"""

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.Management.GlobalPrincipalRoles \
     import principalRolesManager as manager
from Zope.App.Security.Management.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(manager.getPrincipalsForRole(role), [])
        self.assertEqual(manager.getRolesForPrincipal(principal),
                         [])

    def testPrincipalRoleAssign(self):
        role = rregistry.defineRole('ARole', 'A Role').getId()
        principal = self._make_principal()
        manager.assignRoleToPrincipal(role, principal)
        self.assertEqual(manager.getPrincipalsForRole(role),
                         [(principal,Assign)])
        self.assertEqual(manager.getRolesForPrincipal(principal),
                         [(role,Assign)])

    def testPrincipalRoleRemove(self):
        role = rregistry.defineRole('ARole', 'A Role').getId()
        principal = self._make_principal()
        manager.removeRoleFromPrincipal(role, principal)
        self.assertEqual(manager.getPrincipalsForRole(role),
                         [(principal,Remove)])
        self.assertEqual(manager.getRolesForPrincipal(principal),
                         [(role,Remove)])

    def testPrincipalRoleUnset(self):
        role = rregistry.defineRole('ARole', 'A Role').getId()
        principal = self._make_principal()
        manager.removeRoleFromPrincipal(role, principal)
        manager.unsetRoleForPrincipal(role, principal)
        self.assertEqual(manager.getPrincipalsForRole(role),
                         [])
        self.assertEqual(manager.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()
        manager.assignRoleToPrincipal(role1, prin1)
        manager.assignRoleToPrincipal(role2, prin1)
        roles = manager.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')
        manager.assignRoleToPrincipal(role1, prin1)
        manager.assignRoleToPrincipal(role1, prin2)
        principals = manager.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')
        manager.assignRoleToPrincipal(role1, prin1)
        manager.assignRoleToPrincipal(role1, prin2)
        manager.assignRoleToPrincipal(role2, prin1)
        principalsAndRoles = manager.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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testGlobalRolePermissions.py ===
# Copyright (c) 2001 Zope Coporation and Contributors.  All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (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: testGlobalRolePermissions.py,v 1.1.2.1 2002/04/09 16:36:43 caseman Exp $
"""

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.Management.GlobalRolePermissions \
        import rolePermissionsManager as manager
from Zope.App.Security.Management.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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testMementoPrincipalPermissions.py ===
# Copyright (c) 2001 Zope Coporation and Contributors.  All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (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 MementoPrincipalPermissionsManager module."""

import sys
import unittest

from Zope.App.OFS.Memento.IAttributeMementoStorable \
     import IAttributeMementoStorable
from Zope.ComponentArchitecture import provideAdapter
from Zope.App.OFS.Memento.IMementoBag import IMementoBag
from Zope.App.OFS.Memento.AttributeMementoBag import AttributeMementoBag
from Zope.App.Security.PermissionRegistry \
    import permissionRegistry as permregistry
from Zope.App.Security.PrincipalRegistry \
    import principalRegistry as prinregistry
from Zope.App.Security.Management.MementoPrincipalPermissions \
    import MementoPrincipalPermissionsManager 
from Zope.App.Security.Management.Settings import Allow, Deny, Unset
from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup

class Manageable:
    __implements__ = IAttributeMementoStorable

class Test(CleanUp, unittest.TestCase):
    
    def setUp(self):
        CleanUp.setUp(self)
        provideAdapter(IAttributeMementoStorable, IMementoBag, 
                       AttributeMementoBag)   
        
    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 = MementoPrincipalPermissionsManager(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 = MementoPrincipalPermissionsManager(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 = MementoPrincipalPermissionsManager(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 = MementoPrincipalPermissionsManager(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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testMementoPrincipalRoles.py ===
# Copyright (c) 2001 Zope Coporation and Contributors.  All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (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.Memento.IAttributeMementoStorable \
     import IAttributeMementoStorable
from Zope.ComponentArchitecture import provideAdapter
from Zope.App.OFS.Memento.IMementoBag import IMementoBag
from Zope.App.OFS.Memento.AttributeMementoBag import AttributeMementoBag
from Zope.App.Security.RoleRegistry import roleRegistry as rregistry
from Zope.App.Security.PrincipalRegistry import principalRegistry as pregistry
from Zope.App.Security.Management.MementoPrincipalRoles \
        import MementoPrincipalRolesManager
from Zope.App.Security.Management.Settings import Assign, Remove
from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup

class Manageable:
    __implements__ = IAttributeMementoStorable

class Test(CleanUp, unittest.TestCase):
    
    def setUp(self):
        CleanUp.setUp(self)
        provideAdapter(IAttributeMementoStorable, IMementoBag, 
                       AttributeMementoBag)   
                       
    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 = MementoPrincipalRolesManager(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 = MementoPrincipalRolesManager(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 = MementoPrincipalRolesManager(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 = MementoPrincipalRolesManager(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 = MementoPrincipalRolesManager(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 = MementoPrincipalRolesManager(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 = MementoPrincipalRolesManager(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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testMementoRolePermissions.py ===
##############################################################################
#
# Copyright (c) 2001 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.Management.MementoRolePermissions \
     import MementoRolePermissionsManager
from Zope.App.OFS.Memento.IAttributeMementoStorable \
     import IAttributeMementoStorable
from Zope.App.OFS.Memento.IMementoBag import IMementoBag
from Zope.App.OFS.Memento.AttributeMementoBag import AttributeMementoBag
from Zope.ComponentArchitecture \
     import defineService, provideService, provideAdapter
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.Management.Settings import Allow, Deny
from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup

import unittest, sys

class Manageable:
    __implements__ = IAttributeMementoStorable

class Test(CleanUp, unittest.TestCase):

    def setUp(self):
        CleanUp.setUp(self)
        defineService('RoleService', IRoleService)
        defineService('PermissionService', IPermissionService)
        provideService('RoleService', roleRegistry)
        provideService('PermissionService', permissionRegistry)
        provideAdapter(IAttributeMementoStorable, IMementoBag, 
                       AttributeMementoBag)                       

        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 = MementoRolePermissionsManager(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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testPrincipalPermissionsView.py ===
##############################################################################
#
# Copyright (c) 2001 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: testPrincipalPermissionsView.py,v 1.1.2.1 2002/04/09 16:36:44 caseman Exp $
"""

import unittest

from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
from Zope.ComponentArchitecture import defineService, provideService
from Zope.ComponentArchitecture import provideAdapter
from Zope.App.OFS.Memento.IAttributeMementoStorable \
     import IAttributeMementoStorable
from Zope.App.OFS.Memento.IMementoBag import IMementoBag
from Zope.App.OFS.Memento.AttributeMementoBag import AttributeMementoBag
from Zope.App.Security.IPermissionService import IPermissionService
from Zope.App.Security.IAuthenticationService import IAuthenticationService
from Zope.App.Security.Management.IPrincipalPermissions \
        import IPrincipalPermissionsManager
from Zope.App.Security.Management.Settings import Allow, Deny, Unset

class DummyContext:

    __implements__ = IAttributeMementoStorable

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__ = IPrincipalPermissionsManager
    
    def __init__(self, context):
        self._context = context
        if not hasattr(self._context,'principals'):
            self._context.principals = {}
        
    def grantPermissionToPrincipal(self, permission, principal):
        if not self._context.principals.has_key(principal):
            self._context.principals[principal]={}
            
        self._context.principals[principal][permission]=Allow

    def denyPermissionToPrincipal(self, permission, principal):
        if not self._context.principals.has_key(principal):
            self._context.principals[principal]={}
            
        self._context.principals[principal][permission]=Deny

    def unsetPermissionForPrincipal(self, permission, principal):
        if not self._context.principals.has_key(principal):
            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.has_key(permission):
                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(CleanUp, unittest.TestCase):

    def setUp(self):
        self._permissions = []
        self._permissions.append(DummyObject('qux', 'Qux'))
        self._permissions.append(DummyObject('baz', 'Baz'))

        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(IAttributeMementoStorable,
                       IPrincipalPermissionsManager, DummyAdapter)
        provideAdapter(IAttributeMementoStorable, IMementoBag, 
                       AttributeMementoBag) 

    def _makeOne(self):
        from Zope.App.Security.Management.PrincipalPermissionsView \
             import PrincipalPermissionsView
        return PrincipalPermissionsView(DummyContext())

    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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testPrincipalRolesView.py ===
##############################################################################
#
# Copyright (c) 2001 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: testPrincipalRolesView.py,v 1.1.2.1 2002/04/09 16:36:44 caseman Exp $
"""

import unittest

from Zope.Testing.CleanUp import CleanUp # Base class w registry cleanup
from Zope.ComponentArchitecture import defineService, provideService

from Zope.App.Security.IRoleService import IRoleService
from Zope.App.Security.IAuthenticationService import IAuthenticationService

from Zope.App.Security.Management.IPrincipalRoles \
     import IPrincipalRolesManager

class DummyManager:

    __implements__ = IPrincipalRolesManager

    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(CleanUp, unittest.TestCase ):

    def setUp(self):
        self._roles = []
        self._roles.append( DummyObject( 'qux', 'Qux' ) )
        self._roles.append( DummyObject( 'baz', 'Baz' ) )

        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.Management.PrincipalRolesView \
             import PrincipalRolesView
        return PrincipalRolesView( DummyManager() )

    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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testRolePermissionsView.py ===
##############################################################################
#
# Copyright (c) 2001 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.Testing.CleanUp import CleanUp # Base class w registry cleanup
from Zope.ComponentArchitecture import defineService, provideService
from Zope.App.Security.IRoleService import IRoleService
from Zope.App.Security.tests.RoleService import RoleService
from Zope.App.Security.tests.PermissionService import PermissionService
from RolePermissionsManager import RolePermissionsManager
from Zope.App.Security.Management.RolePermissionsView import RolePermissionsView
from Zope.App.Security.IPermissionService import IPermissionService

class Test(CleanUp, unittest.TestCase):

    def setUp(self):
        defineService('RoleService', IRoleService)
        provideService('RoleService', RoleService(
            manager='Manager', member='Member'))
        defineService('PermissionService', IPermissionService)
        provideService('PermissionService', PermissionService(
            read='Read', write='Write'))
        self.view = RolePermissionsView(RolePermissionsManager())

    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())


=== Added File Zope3/lib/python/Zope/App/Security/Management/tests/testSettings.py ===
##############################################################################
# Copyright (c) 2001 Zope Corporation and Contributors.  All Rights Reserved.
# 
# This software is subject to the provisions of the Zope Public License,
# Version 1.1 (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.Management.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())