# -*- coding: iso-8859-15 -*-

import sys
import unittest

glasnostPythonDir = '/usr/local/lib/glasnost-tests'
sys.path.insert(0, glasnostPythonDir)

from GlasnostTestCase import MinimalTestCase

import glasnost.common.system as system
import glasnost.common.faults as faults

import glasnost.proxy.GroupsProxy as Groups
import glasnost.proxy.kinds as kinds
import glasnost.proxy.properties as properties
from glasnost.proxy.tools import getProxyForServerRole


groupsProxy = getProxyForServerRole('groups')

class GroupsTestCase(MinimalTestCase):
    groupsCount = None

    def setUp(self):
        MinimalTestCase.setUp(self)
        self.groupsCount = groupsProxy.getObjectsCount()

    def tearDown(self):
        try:
            if self.groupsCount is not None:
                self.failUnlessEqual(groupsProxy.getObjectsCount(),
                                     self.groupsCount)
        finally:
            MinimalTestCase.tearDown(self)


class AllGroupsTestCase(GroupsTestCase):
    def test01_groupGeneralPublic(self):
        """Test setContains for the general public system group"""

        groupId = system.generalPublicId
        self.failUnlessEqual(Groups.setContains([groupId], ''), 1)

    def test02_generalPublicMemberGroup(self):
        """Test getSetContainedIds for the general public system group"""

        set = [system.generalPublicId]
        self.failUnlessRaises(
                faults.UncountableGroup, Groups.getSetContainedIds,
                set, ['identities'], raiseWhenUncountable = 1)


class UnionGroupsTestCase(GroupsTestCase):
    def test01_groupCreationAndDeletion(self):
        """Test union group creation and deletion"""

        group = Groups.GroupUnion()
        group.language = 'en'
        group.name = 'test01'
        groupId = groupsProxy.addObject(group)
        group = groupsProxy.getObject(groupId)
        groupsProxy.deleteObject(groupId)

    def test02_singleMemberGroup(self):
        """Test union group with a single member"""

        itemId = 'glasnost://localhost/blah/1'

        group = Groups.GroupUnion()
        group.language = 'en'
        group.name = 'test02'
        group.membersSet = [itemId]
        groupId = groupsProxy.addObject(group)

        group = groupsProxy.getObject(groupId)
        self.failUnlessEqual(group.contains(itemId), 1)
        self.failUnlessEqual(Groups.setContains([groupId], itemId), 1)
        groupsProxy.deleteObject(groupId)

suite1 = unittest.makeSuite(AllGroupsTestCase, 'test')
suite2 = unittest.makeSuite(UnionGroupsTestCase, 'test')

allTests = unittest.TestSuite((suite1, suite2))

if __name__ == '__main__':
    unittest.TextTestRunner(verbosity=2).run(allTests)

