[Zope3-checkins] CVS: Zope3/src/zope/app/registration/tests - __init__.py:1.1 iregistry.py:1.1 registrationstack.py:1.1 test_registered.py:1.1 test_registrationmanager.py:1.1 test_registrations.py:1.1 test_registrationstack.py:1.1 test_registrationstatusproperty.py:1.1

Stephan Richter srichter at cosmos.phy.tufts.edu
Sat Mar 13 13:01:20 EST 2004


Update of /cvs-repository/Zope3/src/zope/app/registration/tests
In directory cvs.zope.org:/tmp/cvs-serv27233/src/zope/app/registration/tests

Added Files:
	__init__.py iregistry.py registrationstack.py 
	test_registered.py test_registrationmanager.py 
	test_registrations.py test_registrationstack.py 
	test_registrationstatusproperty.py 
Log Message:


Moved registration code to zope.app.registration. Created module aliases, so
that old ZODBs work.


=== Added File Zope3/src/zope/app/registration/tests/__init__.py ===
# Import this.


=== Added File Zope3/src/zope/app/registration/tests/iregistry.py ===
##############################################################################
#
# Copyright (c) 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.
#
##############################################################################
"""Sample IRegistry Implementation

$Id: iregistry.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""
from zope.app.registration.interfaces import IRegistry
from zope.interface.verify import verifyObject
from zope.app.location import inside

class TestingIRegistry:
    """Base class for testing implementors of IRegistry

    Subclasses must implement:

      - createTestingRegistry()
        that returns a new registry object with no registrations.

        This registration object must be in the context of something
        that is not None.

      - createTestingRegistration()
        that returns a registration object.

    """

    def _assertInContext(self, ob, parent):
        """Assert that we have the proper context

        The container of ob must be the parent, and the parent must
        have some context.

        """
        self.assert_(inside(ob, parent))

    def test_implements_IRegistry(self):
        verifyObject(IRegistry, self.createTestingRegistry())

    def test_queryRegistrationsFor_no_config(self):
        registry = self.createTestingRegistry()
        registration = self.createTestingRegistration()
        self.failIf(registry.queryRegistrationsFor(registration))

        self.assertEqual(
            registry.queryRegistrationsFor(registration, 42),
            42)

    def test_createRegistrationsFor(self):
        registry = self.createTestingRegistry()
        registration = self.createTestingRegistration()
        stack = registry.createRegistrationsFor(registration)

        self.assert_(inside(stack, registry))

        # If we call it again, we should get the same object
        self.assertEqual(registry.createRegistrationsFor(registration),
                         stack)

        self.assert_(inside(stack, registry))

        return stack

    def test_queryRegistrationsFor(self):
        registry = self.createTestingRegistry()
        registration = self.createTestingRegistration()

        cstack = registry.createRegistrationsFor(registration)


        stack = registry.queryRegistrationsFor(registration)
        self.assertEqual(stack, cstack)
        self._assertInContext(stack, registry)

        stack = registry.queryRegistrationsFor(registration, 42)
        self.assertEqual(stack, cstack)
        self._assertInContext(stack, registry)


=== Added File Zope3/src/zope/app/registration/tests/registrationstack.py ===
##############################################################################
#
# Copyright (c) 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.
#
##############################################################################
"""Registration Stack

$Id: registrationstack.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""
from zope.app.registration.registration import RegistrationStatusProperty
from zope.app.container.contained import Contained

__metaclass__ = type

class TestingRegistration(Contained):
    status = RegistrationStatusProperty()

    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        return self.id == getattr(other, 'id', 0)

class TestingRegistrationStack:

    class_ = TestingRegistration

    def __init__(self, *args):
        self._data = args

    def register(self, registration):
        cid = registration.id

        if self._data:
            if cid in self._data:
                return # already registered
        else:
            # Nothing registered. Need to stick None in front so that nothing
            # is active.
            self._data = (None, )

        self._data += (cid, )

    def unregister(self, registration):
        cid = registration.id

        data = self._data
        if data:
            if data[0] == cid:
                # It's active, we need to switch in None
                self._data = (None, ) + data[1:]
            else:
                self._data = tuple([item for item in data if item != cid])

    def registered(self, registration):
        cid = registration.id
        return cid in self._data

    def activate(self, registration):
        if registration is None:
            self._data = (None,) + filter(None, self._data)
            if self._data[-1] is None:
                self._data = self._data[:-1]
            return
        cid = registration.id
        if self._data[0] == cid:
            return # already active

        if self._data[0] is None:
            # Remove leading None marker
            self._data = self._data[1:]

        self._data = (cid, ) + tuple(
            [item for item in self._data if item != cid]
            )

    def deactivate(self, registration):
        cid = registration.id
        if self._data[0] != cid:
            return # already inactive

        # Just stick None on the front
        self._data = (None, ) + self._data

    def active(self):
        if self._data:
            return self.class_(self._data[0])

        return None

    def __nonzero__(self):
        return bool(self._data)

    def info(self):
        result = [{'id': path,
                   'active': False,
                   'registration': self.class_(path),
                   }
                  for path in self._data
                  ]

        if result:
            if result[0]['registration'] is None:
                del result[0]
            else:
                result[0]['active'] = True

        return result


=== Added File Zope3/src/zope/app/registration/tests/test_registered.py ===
##############################################################################
#
# Copyright (c) 2003 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_registered.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""
from unittest import TestCase, TestSuite, main, makeSuite
from zope.app.registration.registration import Registered
from zope.app.interfaces.annotation import IAnnotations
from zope.app.interfaces.traversing import ITraverser
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.interface import implements
from zope.app.container.contained import Contained

class C(dict, Contained):

    __name__ = __parent__ = None
    
    implements(IAnnotations, ITraverser)

    def __init__(self, testobjs={}):
        self.testobjs = testobjs

    def traverse(self, path, default=None, request=None):
        return self.testobjs[path]
        

class TestRegistered(PlacelessSetup, TestCase):

    def testVerifyInterface(self):
        from zope.interface.verify import verifyObject
        from zope.app.registration.interfaces import IRegistered
        obj = Registered(C())
        verifyObject(IRegistered, obj)

    def testBasic(self):
        a_b = 12
        c_d = 24
        c_e = 36
        obj = Registered(C({'/a/b': a_b,
                            '/c/d': c_d,
                            '/c/e': c_e,
                            }))
        self.failIf(obj.usages())
        obj.addUsage('/a/b')
        obj.addUsage('/c/d')
        obj.addUsage('/c/e')
        obj.addUsage('/c/d')
        locs = list(obj.usages())
        locs.sort()
        self.assertEqual(locs, ['/a/b', '/c/d', '/c/e'])
        regs = list(obj.registrations())
        self.assertEqual(len(regs), 3)
        self.assert_(a_b in regs)
        self.assert_(c_d in regs)
        self.assert_(c_e in regs)

        obj.removeUsage('/c/d')
        locs = list(obj.usages())
        locs.sort()
        self.assertEqual(locs, ['/a/b', '/c/e'])
        regs = list(obj.registrations())
        self.assertEqual(len(regs), 2)
        self.assert_(a_b in regs)
        self.assert_(c_d not in regs)
        self.assert_(c_e in regs)

        obj.removeUsage('/c/d')
        locs = list(obj.usages())
        locs.sort()
        self.assertEqual(locs, ['/a/b', '/c/e'])
        self.assertEqual(len(regs), 2)
        self.assert_(a_b in regs)
        self.assert_(c_d not in regs)
        self.assert_(c_e in regs)

    def testRelativeAbsolute(self):
        obj = Registered(C())
        # Hack the object to have a parent path
        obj.pp = "/a/"
        obj.pplen = len(obj.pp)
        obj.addUsage("foo")
        self.assertEqual(obj.usages(), ("/a/foo",))
        obj.removeUsage("/a/foo")
        self.assertEqual(obj.usages(), ())
        obj.addUsage("/a/bar")
        self.assertEqual(obj.usages(), ("/a/bar",))
        obj.removeUsage("bar")
        self.assertEqual(obj.usages(), ())

def test_suite():
    return makeSuite(TestRegistered)

if __name__=='__main__':
    main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/registration/tests/test_registrationmanager.py ===
##############################################################################
#
# Copyright (c) 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_registrationmanager.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""
from unittest import TestCase, main, makeSuite
from zope.app.container.interfaces import IRemoveNotifiable
from zope.app.registration.interfaces import IRegistrationManager
from zope.app.registration.registration import RegistrationManager
from zope.app.site.tests import placefulsetup
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.traversing import traverse
from zope.interface.common.tests.basemapping import BaseTestIEnumerableMapping
from zope.interface.verify import verifyObject
from zope.interface import implements
from zope.app.container.contained import ObjectRemovedEvent

class Undeletable:

    __name__ = __parent__ = None
    
    implements(IRemoveNotifiable)

    def removeNotify(self, event):
        self.was_called = 1


class Test(BaseTestIEnumerableMapping, PlacelessSetup, TestCase):
    """Testing for Registration Manager """

    def setUp(self):
        super(Test, self).setUp()
        self.__manager = manager = RegistrationManager()
        self.names = []
        self.stateDict = {}
        for ltr in 'abcdefghijklmnop':
            name = manager.addRegistration(ltr)
            self.names.append(name)
            self.stateDict[name] = ltr
        n = self.names.pop(9); del manager[n]; del self.stateDict[n] # 'str10'
        n = self.names.pop(7); del manager[n]; del self.stateDict[n] # 'str8'

    def test_implements_IRegistrationManager(self):
        verifyObject(IRegistrationManager, self.__manager)

    def _IEnumerableMapping__stateDict(self):
        # Hook needed by BaseTestIEnumerableMapping
        # also, effectively test __setitem__ and __delitem__.
        return self.stateDict

    def _IEnumerableMapping__sample(self):
        # Hook needed by BaseTestIEnumerableMapping
        # also, effectively test __setitem__ and __delitem__.
        return self.__manager

    def _IEnumerableMapping__absentKeys(self):
        # Hook needed by BaseTestIEnumerableMapping
        # also, effectively test __setitem__ and __delitem__.
        return ['-1', '8', '10', '17', '100', '10000']

    #########################################################
    # Move Top

    def test_moveTop_nothing(self):
        self.__manager.moveTop([])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveTop_1_no_effect(self):
        self.__manager.moveTop([self.names[0]])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveTop_many_no_effect(self):
        names = self.names
        self.__manager.moveTop([names[0], 'str88',
                                names[2], names[1], 'str99'])
        self.assertEqual(
            list(self.__manager.keys()),
            names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveTop_1(self):
        names = self.names[:]
        name = names.pop(2)
        names.insert(0, name)
        self.__manager.moveTop([name])
        self.assertEqual(
            list(self.__manager.keys()),
            names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveTop_many(self):
        names = self.names[:]
        n14 = names.pop(13)
        n13 = names.pop(12)
        n9 = names.pop(9)
        n3 = names.pop(3)
        n2 = names.pop(2)
        n0 = names.pop(0)
        move_names = [n0, n2, 'str88', n3, n9, n13, n14, 'str99']
        self.__manager.moveTop(move_names)
        self.assertEqual(
            list(self.__manager.keys()),
            [n0, n2, n3, n9, n13, n14] + names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveTop_one_element_container(self):
        manager = RegistrationManager()
        name = manager.addRegistration('a')
        manager.moveTop([name])
        self.assertEqual(list(manager.items()), [(name, 'a')])

    #########################################################
    # Move Bottom

    def test_moveBottom_nothing(self):
        self.__manager.moveBottom([])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveBottom_1_no_effect(self):
        self.__manager.moveBottom([self.names[-1]])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveBottom_many_no_effect(self):
        names = self.names
        self.__manager.moveBottom([names[11], 'str88',
                                   names[13], names[12], 'str99'])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveBottom_1(self):
        names = self.names[:]
        name = names.pop(2)
        names.append(name)
        self.__manager.moveBottom([name])
        self.assertEqual(
            list(self.__manager.keys()),
            names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveBottom_many(self):
        names = self.names[:]
        n13 = names.pop(13)
        n12 = names.pop(12)
        n9 = names.pop(9)
        n3 = names.pop(3)
        n2 = names.pop(2)
        n0 = names.pop(0)
        self.__manager.moveBottom(
            [n0, n2, 'str88', n3, n9, n13, n12, 'str99'])
        self.assertEqual(
            list(self.__manager.keys()),
            names + [n0, n2, n3, n9, n12, n13],
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveBottom_one_element_container(self):
        manager = RegistrationManager()
        name = manager.addRegistration('a')
        manager.moveBottom([name])
        self.assertEqual(list(manager.items()), [(name, 'a')])

    #########################################################
    # Move Up

    def test_moveUp_nothing(self):
        self.__manager.moveUp([])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveUp_1_no_effect(self):
        self.__manager.moveUp([self.names[0]])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveUp_many_no_effect(self):
        names = self.names
        self.__manager.moveUp([names[0], 'str88', names[2], names[1], 'str99'])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveUp_1(self):
        names = self.names[:]
        n2 = names.pop(2)
        names.insert(1, n2)
        self.__manager.moveUp([n2])
        self.assertEqual(
            list(self.__manager.keys()),
            names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveUp_many(self):
        names = self.names
        self.__manager.moveUp(
            [names[0], names[2], 'str88', names[3], names[8],
             names[13], names[12], 'str99'])
        self.assertEqual(
            list(self.__manager.keys()),
            [names[0], names[2], names[3], names[1], names[4],
             names[5], names[6], names[8], names[7], names[9],
             names[10], names[12], names[13], names[11]],
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveUp_one_element_container(self):
        manager = RegistrationManager()
        name = manager.addRegistration('a')
        manager.moveUp([name])
        self.assertEqual(list(manager.items()), [(name, 'a')])

    #########################################################
    # Move Down

    def test_moveDown_nothing(self):
        self.__manager.moveDown([])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveDown_1_no_effect(self):
        self.__manager.moveDown([self.names[-1]])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveDown_many_no_effect(self):
        names = self.names
        self.__manager.moveDown([names[13], 'str88',
                                 names[11], names[12], '99'])
        self.assertEqual(
            list(self.__manager.keys()),
            self.names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveDown_1(self):
        names = self.names[:]
        n2 = names.pop(2)
        names.insert(3, n2)
        self.__manager.moveDown([n2])
        self.assertEqual(
            list(self.__manager.keys()),
            names,
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveDown_many(self):
        names = self.names
        self.__manager.moveDown(
            [names[0], names[2], 'str88', names[3],
             names[8], names[13], names[12], 'str99'])
        self.assertEqual(
            list(self.__manager.keys()),
            [names[1], names[0], names[4], names[2], names[3],
             names[5], names[6], names[7], names[9], names[8],
             names[10], names[11], names[12], names[13]],
            )

        # Make sure we still have the right items
        self.test_items()

    def test_moveDown_one_element_container(self):
        manager = RegistrationManager()
        name = manager.addRegistration('a')
        manager.moveDown([name])
        self.assertEqual(list(manager.items()), [(name, 'a')])

    #########################################################

    def test_removeNotify(self):
        manager = RegistrationManager()
        thingy = Undeletable()
        manager['xyzzy'] = thingy
        event = ObjectRemovedEvent(manager, 'xxx', 'yyy')
        manager.removeNotify(event)
        self.failUnless(thingy.was_called)

class RegistrationManagerContainerTests(placefulsetup.PlacefulSetup):


    def test_getRegistrationManager(self):
        sm = self.buildFolders(site=True)
        default = traverse(sm, 'default')
        self.assertEqual(default.getRegistrationManager(),
                         default['RegistrationManager'])
        default['xxx'] = RegistrationManager()
        del default['RegistrationManager']
        self.assertEqual(default.getRegistrationManager(),
                         default['xxx'])


#       Can't test empty because there's no way to make it empty.
##         del default[name]
##         self.assertRaises(Exception,
##                           default.getRegistrationManager)

    def test_cant_remove_last_cm(self):
        sm = self.buildFolders(site=True)
        default = traverse(sm, 'default')
        self.assertRaises(Exception,
                          default.__delitem__, 'registration')
        default['xxx'] = RegistrationManager()
        del default['RegistrationManager']


def test_suite():
    return makeSuite(Test)

if __name__=='__main__':
    main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/registration/tests/test_registrations.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.
#
##############################################################################
"""Unit tests for registration classes

$Id: test_registrations.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""

from unittest import TestCase, TestSuite, main, makeSuite

from zope.interface import Interface, implements
from zope.app.registration.interfaces import UnregisteredStatus
from zope.app.registration.interfaces import RegisteredStatus
from zope.app.registration.interfaces import ActiveStatus
from zope.app.interfaces.dependable import DependencyError
from zope.app.registration.registration import \
     SimpleRegistration, ComponentRegistration
from zope.app.site.tests.placefulsetup import PlacefulSetup
from zope.app.interfaces.dependable import IDependable
from zope.app.traversing import traverse
from zope.security.proxy import Proxy
from zope.app.container.contained import ObjectRemovedEvent

class ITestComponent(Interface):
    pass

class ComponentStub:

    implements(IDependable)

    _dependents = ()

    def addDependent(self, location):
        self._dependents = tuple(
            [d for d in self._dependents if d != location]
            +
            [location]
            )

    def removeDependent(self, location):
        self._dependents = tuple(
            [d for d in self._dependents if d != location]
            )

    def dependents(self):
        return self._dependents


class TestSimpleRegistration(TestCase):

    def setUp(self):
        # We can't use the status property on a SimpleRegistration instance.
        # we disable it for these tests
        self.__oldprop = SimpleRegistration.status
        del SimpleRegistration.status

    def tearDown(self):
        # Restore the status prop
        SimpleRegistration.status = self.__oldprop

    def test_removeNotify(self):
        cfg = SimpleRegistration()

        # cannot delete an active registration
        cfg.status = ActiveStatus
        event = ObjectRemovedEvent(cfg, None, 'somename')
        self.assertRaises(DependencyError, cfg.removeNotify, event)

        # deletion of a registered registration causes it to become
        # unregistered
        cfg.status = RegisteredStatus
        cfg.removeNotify(event)
        self.assertEquals(cfg.status, UnregisteredStatus)


class TestComponentRegistration(TestSimpleRegistration, PlacefulSetup):

    def setUp(self):
        TestSimpleRegistration.setUp(self)
        PlacefulSetup.setUp(self, site=True)
        self.name = 'foo'

    def test_getComponent(self):
        # set up a component
        name, component = 'foo', object()
        self.rootFolder[name] = component
        # set up a registration
        cfg = ComponentRegistration("/"+name)
        cfg.__parent__ = self.rootFolder
        # check that getComponent finds the registration
        self.assertEquals(cfg.getComponent(), component)

    def test_getComponent_permission(self):
        # set up a component
        name, component = 'foo', object()
        self.rootFolder[name] = component
        # set up a registration
        cfg = ComponentRegistration("/"+name, 'zope.TopSecret')
        cfg.getInterface = lambda: ITestComponent
        cfg.__parent__ = self.rootFolder
        # check that getComponent finds the registration
        result = cfg.getComponent()
        self.assertEquals(result, component)
        self.failUnless(type(result) is Proxy)

    def test_addNotify(self):
        # set up a component
        name, component = 'foo', ComponentStub()
        self.rootFolder[name] = component
        # set up a registration
        cfg = ComponentRegistration("/"+name)
        self.rootFolder['cfg'] = cfg
        cfg = traverse(self.rootFolder, 'cfg')
        # check that the dependency tracking works
        self.assertEquals(component.dependents(), ('/cfg',))

    def test_removeNotify_dependents(self):
        # set up a component
        name, component = 'foo', ComponentStub()
        self.rootFolder[name] = component
        component.addDependent('/cfg')
        # set up a registration
        cfg = ComponentRegistration("/"+name)
        cfg.status = UnregisteredStatus
        self.rootFolder['cfg'] = cfg
        cfg = traverse(self.rootFolder, 'cfg')
        # simulate IRemoveNotifiable
        event = ObjectRemovedEvent(cfg, self.rootFolder, 'cfg')
        cfg.removeNotify(event)
        # check that the dependency tracking works
        self.assertEquals(component.dependents(), ())

def test_suite():
    return TestSuite((
        makeSuite(TestSimpleRegistration),
        makeSuite(TestComponentRegistration),
        ))

if __name__=='__main__':
    main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/registration/tests/test_registrationstack.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.
#
##############################################################################
"""Registration Stack tests

$Id: test_registrationstack.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""
from unittest import TestCase, TestSuite, main, makeSuite
from zope.app.site.tests.placefulsetup import PlacefulSetup
from zope.app.registration.registration import RegistrationStack
from zope.app.traversing import traverse

class Registration:

    active = 0
    registry = None

    def activated(self):
        if (self.registry is not None) and (self.registry.active() != self):
            raise AssertionError("Told active but not the active registration")
        self.active += 1

    def deactivated(self):
        if (self.registry is not None) and (self.registry.active() == self):
            raise AssertionError(
                "Told deactivated but still the active registration")
        self.active -= 1


class Test(PlacefulSetup, TestCase):

    def setUp(self):
        PlacefulSetup.setUp(self, site=True)
        root = self.rootFolder
        self.__default = traverse(root, "++etc++site/default")
        self.__registry = RegistrationStack(root)

    def __config(self, name):
        self.__default[name] = Registration()
        return self.__default[name]

    def test_register_and_registered_and_nonzero_and_active(self):
        registry = self.__registry

        self.assertEqual(registry.active(), None)

        self.failIf(registry)
        self.__c1 = c1 = self.__config("1")
        c1.registry = registry
        registry.register(c1)
        self.failUnless(registry)
        self.failUnless(registry.registered(c1))
        self.assertEqual(c1.active, 0)

        self.assertEqual(registry.active(), None)

        self.__c2 = c2 = self.__config("2")
        c2.registry = registry
        self.failIf(registry.registered(c2))
        registry.register(c2)
        self.failUnless(registry)
        self.failUnless(registry.registered(c2))
        self.assertEqual(c2.active, 0)


    def test_unregister_and_registered_and_nonzero(self):
        # reuse registration test to set things up (more)
        self.test_register_and_registered_and_nonzero_and_active()

        registry = self.__registry

        c1 = self.__c1
        registry.unregister(c1)
        self.failIf(registry.registered(c1))
        self.assertEqual(c1.active, 0)

        c2 = self.__c2
        registry.unregister(c2)
        self.failIf(registry.registered(c2))
        self.assertEqual(c2.active, 0)

        self.failIf(registry)

    def test_activate_and_active(self):
        # reuse registration test to set things up (more)
        self.test_register_and_registered_and_nonzero_and_active()

        registry = self.__registry
        self.assertEqual(registry.active(), None)

        c1 = self.__c1
        c2 = self.__c2

        registry.activate(c2)
        self.assertEqual(c1.active, 0)
        self.failUnless(registry.registered(c1))
        self.assertEqual(c2.active, 1)
        self.failUnless(registry.registered(c2))
        self.assertEqual(registry.active(), c2)

        registry.activate(c2)
        self.assertEqual(c1.active, 0)
        self.failUnless(registry.registered(c1))
        self.assertEqual(c2.active, 1)
        self.failUnless(registry.registered(c2))
        self.assertEqual(registry.active(), c2)

        registry.activate(c1)
        self.assertEqual(c1.active, 1)
        self.failUnless(registry.registered(c1))
        self.assertEqual(c2.active, 0)
        self.failUnless(registry.registered(c2))
        self.assertEqual(registry.active(), c1)

    def test_activate_none(self):
        self.test_activate_and_active()

        registry = self.__registry
        c1 = self.__c1
        c2 = self.__c2

        registry.activate(None)

        self.assertEqual(c1.active, 0)
        self.failUnless(registry.registered(c1))
        self.assertEqual(c2.active, 0)
        self.failUnless(registry.registered(c2))
        self.assertEqual(registry.active(), None)

    def test_activate_unregistered(self):
        registry = self.__registry
        self.assertRaises(ValueError, registry.activate, self.__config('3'))
        self.test_activate_and_active()
        self.assertRaises(ValueError, registry.activate, self.__config('4'))

    def test_deactivate(self):
        self.test_activate_and_active()

        registry = self.__registry
        c1 = self.__c1
        c2 = self.__c2
        self.assertEqual(registry.active(), c1)

        registry.deactivate(c2)
        self.assertEqual(c2.active, 0)
        self.assertEqual(registry.active(), c1)

        registry.deactivate(c1)
        self.assertEqual(c1.active, 0)
        self.assertEqual(c2.active, 1)
        self.assertEqual(registry.active(), c2)

        self.failUnless(registry.registered(c1))
        self.failUnless(registry.registered(c2))

    def test_unregister_active(self):
        self.test_activate_and_active()

        registry = self.__registry
        c1 = self.__c1
        c2 = self.__c2
        self.assertEqual(registry.active(), c1)

        registry.unregister(c1)
        self.assertEqual(c1.active, 0)
        self.assertEqual(c2.active, 1)
        self.assertEqual(registry.active(), c2)

        self.failIf(registry.registered(c1))
        self.failUnless(registry.registered(c2))

    def test_deactivate_unregistered(self):
        registry = self.__registry
        self.assertRaises(ValueError, registry.deactivate, self.__config('3'))

    def test_info(self):
        self.test_activate_and_active()

        registry = self.__registry
        c1 = self.__c1
        c2 = self.__c2

        info = registry.info()
        self.assertEqual(
            info,
            [
              {'id': 'default/1',
               'active': True,
               'registration': c1,
               },
              {'id': 'default/2',
               'active': False,
               'registration': c2,
               },
              ])

        registry.deactivate(c1)

        info = registry.info()
        self.assertEqual(
            info,
            [
              {'id': 'default/2',
               'active': True,
               'registration': c2,
               },
              {'id': 'default/1',
               'active': False,
               'registration': c1,
               },
              ])

        info = registry.info(True)
        self.assertEqual(
            info,
            [
              {'id': 'default/2',
               'active': True,
               'registration': c2,
               },
              {'id': '',
               'active': False,
               'registration': None,
               },
              {'id': 'default/1',
               'active': False,
               'registration': c1,
               },
              ])

    def test_avoid_duplicate_activation(self):
        # Test for a specific bug that used to exist:
        # when unregistering an inactive registration, don't
        # re-activate the registration that's already active
        c1 = self.__config('1')
        c2 = self.__config('2')
        registry = self.__registry
        registry.register(c1)
        registry.register(c2)
        registry.activate(c1)
        self.assertEqual(c1.active, 1)
        self.assertEqual(c2.active, 0)
        registry.unregister(c2)
        self.assertEqual(c1.active, 1)
        self.assertEqual(c2.active, 0)


def test_suite():
    return TestSuite((
        makeSuite(Test),
        ))

if __name__=='__main__':
    main(defaultTest='test_suite')


=== Added File Zope3/src/zope/app/registration/tests/test_registrationstatusproperty.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.
#
##############################################################################
"""Registration Status Property Tests

$Id: test_registrationstatusproperty.py,v 1.1 2004/03/13 18:01:18 srichter Exp $
"""
from unittest import TestCase, TestSuite, main, makeSuite
from zope.component.interfaces import IServiceService
from zope.app.site.tests.placefulsetup import PlacefulSetup
from zope.app.registration.tests.registrationstack import TestingRegistration
from zope.app.registration.tests.registrationstack import \
     TestingRegistrationStack
from zope.app.registration.interfaces import RegisteredStatus
from zope.app.registration.interfaces import UnregisteredStatus
from zope.app.registration.interfaces import ActiveStatus
from zope.app.registration.interfaces import NoLocalServiceError
from zope.component.exceptions import ComponentLookupError
from zope.interface import implements
from zope.app.container.contained import contained

class TestingRegistration(TestingRegistration):
    serviceType = "Services"
    service_type = "Test"

class PassiveRegistration(TestingRegistration):
    serviceType = "NoSuchService"

class UtilityRegistration(TestingRegistration):
    serviceType = "Utilities"

class TestingRegistrationStack(TestingRegistrationStack):
    class_ = TestingRegistration

class TestingServiceManager:

    implements(IServiceService) # I lied

    registry = None

    def getService(self, name):
        if name in ("Services", "Utilities"):
            return self
        raise ComponentLookupError("Wrong service name", name)

    def queryService(self, name, default=None):
        if name in ("Services", "Utilities"):
            return self
        else:
            return default

    def queryLocalService(self, name, default=None):
        if name == "Services":
            return self
        else:
            return default

    def queryRegistrationsFor(self, registration, default=None):
        if registration.service_type != "Test":
            raise ValueError("Bad service type", registration.service_type)
        return self.registry

    def createRegistrationsFor(self, registration):
        if registration.service_type != "Test":
            raise ValueError("Bad service type", registration.service_type)
        self.registry = TestingRegistrationStack()
        return self.registry


class Test(PlacefulSetup, TestCase):

    def setUp(self):
        PlacefulSetup.setUp(self, folders=True)
        self.__sm = TestingServiceManager()
        self.rootFolder.setSiteManager(self.__sm)

    def test_property(self):

        configa = contained(TestingRegistration('a'), self.rootFolder)
        self.assertEqual(configa.status, UnregisteredStatus)

        configa.status = RegisteredStatus
        self.assertEqual(self.__sm.registry._data, (None, 'a'))
        self.assertEqual(configa.status, RegisteredStatus)

        configa.status = ActiveStatus
        self.assertEqual(self.__sm.registry._data, ('a', ))
        self.assertEqual(configa.status, ActiveStatus)

        configb = contained(TestingRegistration('b'), self.rootFolder)
        self.assertEqual(self.__sm.registry._data, ('a', ))
        self.assertEqual(configb.status, UnregisteredStatus)

        configb.status = RegisteredStatus
        self.assertEqual(self.__sm.registry._data, ('a', 'b'))
        self.assertEqual(configb.status, RegisteredStatus)

        configc = contained(TestingRegistration('c'), self.rootFolder)
        self.assertEqual(configc.status, UnregisteredStatus)
        self.assertEqual(self.__sm.registry._data, ('a', 'b'))

        configc.status = RegisteredStatus
        self.assertEqual(self.__sm.registry._data, ('a', 'b', 'c'))
        self.assertEqual(configc.status, RegisteredStatus)

        configc.status = ActiveStatus
        self.assertEqual(self.__sm.registry._data, ('c', 'a', 'b'))
        self.assertEqual(configc.status, ActiveStatus)

        configc.status = UnregisteredStatus
        self.assertEqual(self.__sm.registry._data, (None, 'a', 'b'))
        self.assertEqual(configc.status, UnregisteredStatus)
        self.assertEqual(configb.status, RegisteredStatus)
        self.assertEqual(configa.status, RegisteredStatus)

    def test_passive(self):
        # scenario:
        #   1. create and configure an SQLConnectionService
        #   2. create and configure a database adapter&connection
        #   3. disable SQLConnectionService
        # now the ConnectionRegistration.status cannot access the
        # SQLConnectionService

        configa = contained(PassiveRegistration('a'), self.rootFolder)
        self.assertEqual(configa.status, UnregisteredStatus)

        try:
            configa.status = RegisteredStatus
        except NoLocalServiceError:
            self.assertEqual(configa.status, UnregisteredStatus)
        else:
            self.fail("should complain about missing service")

        try:
            configa.status = ActiveStatus
        except NoLocalServiceError:
            self.assertEqual(configa.status, UnregisteredStatus)
        else:
            self.fail("should complain about missing service")


        # we should also get an error if there *is a matching service,
        # not it is non-local

        configa = contained(UtilityRegistration('a'), self.rootFolder)
        self.assertEqual(configa.status, UnregisteredStatus)

        try:
            configa.status = RegisteredStatus
        except NoLocalServiceError:
            self.assertEqual(configa.status, UnregisteredStatus)
        else:
            self.fail("should complain about missing service")

        try:
            configa.status = ActiveStatus
        except NoLocalServiceError:
            self.assertEqual(configa.status, UnregisteredStatus)
        else:
            self.fail("should complain about missing service")


def test_suite():
    return TestSuite((
        makeSuite(Test),
        ))

if __name__=='__main__':
    main(defaultTest='test_suite')




More information about the Zope3-Checkins mailing list