[Zope3-checkins] CVS: Zope3/src/zope/app/browser/security/grants/tests - __init__.py:1.1.2.1 permissionservice.py:1.1.2.1 rolepermissionmanager.py:1.1.2.1 roleservice.py:1.1.2.1 test_principalpermissionview.py:1.1.2.1 test_principalroleview.py:1.1.2.1 test_rolepermissionview.py:1.1.2.1

Jim Fulton jim@zope.com
Mon, 23 Dec 2002 14:31:13 -0500


Update of /cvs-repository/Zope3/src/zope/app/browser/security/grants/tests
In directory cvs.zope.org:/tmp/cvs-serv19908/zope/app/browser/security/grants/tests

Added Files:
      Tag: NameGeddon-branch
	__init__.py permissionservice.py rolepermissionmanager.py 
	roleservice.py test_principalpermissionview.py 
	test_principalroleview.py test_rolepermissionview.py 
Log Message:
Initial renaming before debugging

=== Added File Zope3/src/zope/app/browser/security/grants/tests/__init__.py ===
#
# This file is necessary to make this directory a package.


=== Added File Zope3/src/zope/app/browser/security/grants/tests/permissionservice.py ===
##############################################################################
#
# 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: permissionservice.py,v 1.1.2.1 2002/12/23 19:31:11 jim Exp $
"""

from zope.app.interfaces.security import IPermissionService
from zope.app.interfaces.security 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()


=== Added File Zope3/src/zope/app/browser/security/grants/tests/rolepermissionmanager.py ===
##############################################################################
#
# 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 that has no context.

$Id: rolepermissionmanager.py,v 1.1.2.1 2002/12/23 19:31:11 jim Exp $
"""

from zope.component import getAdapter
from zope.app.interfaces.security import IRolePermissionManager
from zope.app.interfaces.security import IRolePermissionMap
from zope.app.security.grants.localsecuritymap import LocalSecurityMap
from zope.app.security.settings import Allow, Deny, Unset

class RolePermissionManager:
    """
    provide adapter that manages role permission data in an object attribute
    """

    __implements__ = IRolePermissionManager, IRolePermissionMap

    def __init__(self):
        self._rp = LocalSecurityMap()

    def grantPermissionToRole(self, permission_id, role_id):
        ''' See the interface IRolePermissionManager '''
        rp = self._getRolePermissions(create=1)
        rp.addCell(permission_id, role_id, Allow)

    def denyPermissionToRole(self, permission_id, role_id):
        ''' See the interface IRolePermissionManager '''
        rp = self._getRolePermissions(create=1)
        rp.addCell(permission_id, role_id, Deny)

    def unsetPermissionFromRole(self, permission_id, role_id):
        ''' See the interface IRolePermissionManager '''
        rp = self._getRolePermissions()
        # Only unset if there is a security map, otherwise, we're done
        if rp:
            rp.delCell(permission_id, role_id)

    def getRolesForPermission(self, permission_id):
        '''See interface IRolePermissionMap'''
        rp = self._getRolePermissions()
        if rp:
            return rp.getRow(permission_id)
        else:
            return []

    def getPermissionsForRole(self, role_id):
        '''See interface IRolePermissionMap'''
        rp = self._getRolePermissions()
        if rp:
            return rp.getCol(role_id)
        else:
            return []

    def getRolesAndPermissions(self):
        '''See interface IRolePermissionMap'''
        rp = self._getRolePermissions()
        if rp:
            return rp.getAllCells()
        else:
            return []

    def getSetting(self, permission_id, role_id):
        '''See interface IRolePermissionMap'''
        rp = self._getRolePermissions()
        if rp:
            return rp.getCell(permission_id, role_id)
        else:
            return Unset

    def _getRolePermissions(self, create=0):
        """Get the role permission map stored in the context, optionally
           creating one if necessary"""
        return self._rp




=== Added File Zope3/src/zope/app/browser/security/grants/tests/roleservice.py ===
##############################################################################
#
# 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: roleservice.py,v 1.1.2.1 2002/12/23 19:31:11 jim Exp $
"""

from zope.app.interfaces.security import IRoleService
from zope.app.interfaces.security 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()


=== Added File Zope3/src/zope/app/browser/security/grants/tests/test_principalpermissionview.py ===
##############################################################################
#
# 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: test_principalpermissionview.py,v 1.1.2.1 2002/12/23 19:31:11 jim Exp $
"""

import unittest

from zope.component import getService, getServiceManager
from zope.app.interfaces.annotation import IAttributeAnnotatable
from zope.app.interfaces.annotation import IAnnotations
from zope.app.attributeannotations import AttributeAnnotations
from zope.app.interfaces.security import IPermissionService
from zope.app.interfaces.security import IAuthenticationService
from zope.app.interfaces.security \
        import IPrincipalPermissionManager
from zope.app.interfaces.security import IPrincipalPermissionMap
from zope.app.security.settings import Allow, Deny, Unset
from zope.app.services.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(
                 'Permissions', IPermissionService)
        provideService('Permissions',
                 DummyPermissionService(self._permissions))

        defineService('Authentication',
                 IAuthenticationService)

        self._principals = []
        self._principals.append(DummyObject('foo', 'Foo'))
        self._principals.append(DummyObject('bar', 'Bar'))

        provideService('Authentication',
            DummyAuthenticationService(principals = self._principals))
        provideAdapter=getService(None,'Adapters').provideAdapter
        provideAdapter(IAttributeAnnotatable,
                       IPrincipalPermissionManager, DummyAdapter)
        provideAdapter(
            IAttributeAnnotatable, IAnnotations, AttributeAnnotations)

    def _makeOne(self):
        from zope.app.browser.security.grants.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())


=== Added File Zope3/src/zope/app/browser/security/grants/tests/test_principalroleview.py ===
##############################################################################
#
# 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: test_principalroleview.py,v 1.1.2.1 2002/12/23 19:31:11 jim Exp $
"""

import unittest

from zope.app.services.tests.placefulsetup\
           import PlacefulSetup
from zope.component import getServiceManager

from zope.app.interfaces.security import IRoleService
from zope.app.interfaces.security import IAuthenticationService

from zope.app.interfaces.security import IPrincipalRoleManager
from zope.app.interfaces.security import IPrincipalRoleMap
from zope.publisher.browser import TestRequest

class DummySetting:
    def __init__(self, name):
        self._name = name
    def getName(self):
        return self._name

class DummyManager:

    __implements__ = IPrincipalRoleManager

    def getSetting(self, role, principal):
        return DummySetting('%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, name):
        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('Roles', IRoleService)
        provideService('Roles'
                      , DummyRoleService(roles = self._roles))

        defineService('Authentication', IAuthenticationService)

        self._principals = []
        self._principals.append(DummyObject('foo', 'Foo'))
        self._principals.append(DummyObject('bar', 'Bar'))

        provideService('Authentication',
            DummyAuthenticationService(principals = self._principals))

    def _makeOne(self):
        from zope.app.browser.security.grants.principalroleview \
             import PrincipalRoleView
        return PrincipalRoleView(DummyManager(), TestRequest())

    def testRoles(self):
        view = self._makeOne()
        roles = list(view.getAllRoles())
        self.assertEqual(len(roles), 2)

        ids = map(lambda x: x.getId(), self._roles)

        for role in roles:
            self.failUnless(role.getId() in ids)

    def testPrincipals(self):
        view = self._makeOne()
        principals = list(view.getAllPrincipals())
        self.assertEqual(len(principals), 2)

        ids = map(lambda x: x.getId(), self._principals)

        for principal in principals:
            self.failUnless(principal.getId() in ids, (principal, ids))

    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 p in grid.principalIds():
            self.failUnless(p in p_ids)

        for r in grid.roleIds():
            self.failUnless(r in r_ids)

        map = DummyManager()

        grid_entries = [(r, p, map.getSetting(r, p).getName())
                        for r in grid.roleIds()
                        for p in grid.principalIds()
                        ]

        for r, p, setting in grid_entries:
            self.assertEquals(setting, grid.getValue(p, r))


def test_suite():
    loader=unittest.TestLoader()
    return loader.loadTestsFromTestCase(Test)

if __name__=='__main__':
    unittest.TextTestRunner().run(test_suite())


=== Added File Zope3/src/zope/app/browser/security/grants/tests/test_rolepermissionview.py ===
##############################################################################
#
# 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.services.tests.placefulsetup\
           import PlacefulSetup
from zope.component import getServiceManager
from zope.app.interfaces.security import IRoleService
from zope.app.browser.security.grants.tests.roleservice import RoleService
from zope.app.browser.security.grants.tests.permissionservice import PermissionService
from zope.app.browser.security.grants.tests.rolepermissionmanager import RolePermissionManager
from zope.app.browser.security.grants.rolepermissionview \
     import RolePermissionView
from zope.app.interfaces.security import IPermissionService

class Test(PlacefulSetup, unittest.TestCase):

    def setUp(self):
        PlacefulSetup.setUp(self)
        defineService=getServiceManager(None).defineService
        provideService=getServiceManager(None).provideService
        defineService('Roles', IRoleService)
        provideService('Roles', RoleService(
            manager='Manager', member='Member'))
        defineService('Permissions', IPermissionService)
        provideService('Permissions', 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 testMatrix(self):
        roles = self.view.roles()
        permissions = self.view.permissions()

        #         manager  member
        # read       +
        # write      .       -
        REQ = {
            'p0': 'read', 'p1': 'write',
            'r0': 'manager', 'r1': 'member',
            'p0r0': 'Allow',
            'p1r0': 'Unset', 'p1r1': 'Deny',
            }
        self.view.request = REQ # XXX yuck
        self.view.action(testing=1)
        permissionRoles = self.view.permissionRoles()
        for ip in range(len(permissionRoles)):
            permissionRole = permissionRoles[ip]
            rset = permissionRole.roleSettings()
            for ir in range(len(rset)):
                setting = rset[ir]
                r = roles[ir].getId()
                p = permissions[ip].getId()
                if setting == 'Allow':
                    self.failUnless(r == 'manager' and p == 'read')
                elif setting == 'Deny':
                    self.failUnless(r == 'member' and p == 'write')
                else:
                    self.failUnless(setting == 'Unset')

        #         manager  member
        # read       -
        # write      +
        REQ = {
            'p0': 'read', 'p1': 'write',
            'r0': 'manager', 'r1': 'member',
            'p0r0': 'Deny',
            'p1r0': 'Allow', 'p1r1': 'Unset'
            }
        self.view.request = REQ # XXX yuck
        self.view.action(testing=1)
        permissionRoles = self.view.permissionRoles()
        for ip in range(len(permissionRoles)):
            permissionRole = permissionRoles[ip]
            rset = permissionRole.roleSettings()
            for ir in range(len(rset)):
                setting = rset[ir]
                r = roles[ir].getId()
                p = permissions[ip].getId()
                if setting == 'Allow':
                    self.failUnless(r == 'manager' and p == 'write')
                elif setting == 'Deny':
                    self.failUnless(r == 'manager' and p == 'read')
                else:
                    self.failUnless(setting == 'Unset')

    def testPermissionRoles(self):
        self.view.update_permission(permission_id='write',
                                    settings=['Allow', 'Unset'],
                                    testing=1)
        permission = self.view.permissionForID('write')
        settings = permission.roleSettings()
        self.assertEquals(settings, ['Allow', 'Unset'])


        self.view.update_permission(permission_id='write',
                                    settings=['Unset', 'Deny'],
                                    testing=1)
        permission = self.view.permissionForID('write')
        settings = permission.roleSettings()
        self.assertEquals(settings, ['Unset', 'Deny'])

        self.assertRaises(ValueError,
                          self.view.update_permission,
                          permission_id='write',
                          settings=['Unset', 'foo'],
                          testing=1)

    def testRolePermissions(self):
        REQ={'Allow': ['read'],
             'Deny': ['write']}
        self.view.request = REQ # XXX yuck
        self.view.update_role(role_id='member',
                              testing=1)
        role = self.view.roleForID('member')
        pinfos = role.permissionsInfo()
        for pinfo in pinfos:
            pid = pinfo['id']
            if pid == 'read':
                self.assertEquals(pinfo['setting'], 'Allow')
            if pid == 'write':
                self.assertEquals(pinfo['setting'], 'Deny')

        REQ={'Allow': [],
             'Deny': ['read']}
        self.view.request = REQ # XXX yuck
        self.view.update_role(role_id='member',
                              testing=1)
        role = self.view.roleForID('member')
        pinfos = role.permissionsInfo()
        for pinfo in pinfos:
            pid = pinfo['id']
            if pid == 'read':
                self.assertEquals(pinfo['setting'], 'Deny')
            if pid == 'write':
                self.assertEquals(pinfo['setting'], 'Unset')


def test_suite():
    loader=unittest.TestLoader()
    return loader.loadTestsFromTestCase(Test)

if __name__=='__main__':
    unittest.TextTestRunner().run(test_suite())