#
# Hotfix tests
#

import os, sys
if __name__ == '__main__':
    execfile(os.path.join(sys.path[0], 'framework.py'))

from Testing import ZopeTestCase
from Products.CMFPlone.tests import PloneTestCase

ZopeTestCase.installProduct('PloneHotfix20060410')

from AccessControl import Unauthorized

from Products.PloneHotfix20060410 import SetOwnProperties
from Products.PloneHotfix20060410 import SetOwnPassword


class TestMethodProtection(PloneTestCase.PloneTestCase):
    # MembershipTool is missing security declarations
    # http://dev.plone.org/plone/ticket/5432

    _unprotected = (
        'changeMemberPortrait',
        'deletePersonalPortrait',
        'testCurrentPassword',
    )

    def afterSetUp(self):
        self.membership = self.portal.portal_membership

    def assertUnprotected(self, object, method):
        self.logout()
        object.restrictedTraverse(method)

    def assertProtected(self, object, method):
        self.logout()
        self.assertRaises(Unauthorized, object.restrictedTraverse, method)

    for method in _unprotected:
        exec "def testUnprotected_%s(self):" \
             "    self.assertProtected(self.membership, '%s')" % (method, method)

        exec "def testMemberAccessible_%s(self):" \
             "    self.membership.restrictedTraverse('%s')" % (method, method)


class TestRoleAssignments(PloneTestCase.PloneTestCase):
    # Make sure we did not change global assignments

    def getRolesOfPermission(self, permission, context):
        roles = context.rolesOfPermission(permission)
        roles = [x['name'] for x in roles if x['selected']]
        return roles

    def assertRolesOfPermission(self, roles, permission, context):
        lhs = list(roles)[:]
        lhs.sort()
        rhs = self.getRolesOfPermission(permission, context)
        rhs.sort()
        self.assertEqual(lhs, rhs)

    def testSetOwnProperties(self):
        self.assertRolesOfPermission(['Authenticated', 'Manager'],
                                    SetOwnProperties, self.portal)

    def testSetOwnPassword(self):
        self.assertRolesOfPermission(['Authenticated', 'Manager'],
                                    SetOwnPassword, self.portal)

    def testSetOwnPropertiesApp(self):
        self.assertRolesOfPermission(['Manager'],
                                    SetOwnProperties, self.app)

    def testSetOwnPasswordApp(self):
        self.assertRolesOfPermission(['Manager'],
                                    SetOwnPassword, self.app)


def test_suite():
    from unittest import TestSuite, makeSuite
    suite = TestSuite()
    suite.addTest(makeSuite(TestMethodProtection))
    suite.addTest(makeSuite(TestRoleAssignments))
    return suite

if __name__ == '__main__':
    framework()
