[Zope3-checkins] CVS: Zope3/src/zope/products/statictree/tests - __init__.py:1.1 basetest.py:1.1 test_adapters.py:1.1 test_browser.py:1.1 test_encoder.py:1.1 test_filters.py:1.1 test_node.py:1.1

Philipp von Weitershausen philikon at philikon.de
Fri Jan 16 07:39:06 EST 2004


Update of /cvs-repository/Zope3/src/zope/products/statictree/tests
In directory cvs.zope.org:/tmp/cvs-serv18109/tests

Added Files:
	__init__.py basetest.py test_adapters.py test_browser.py 
	test_encoder.py test_filters.py test_node.py 
Log Message:
Checked the 'statictree' product in. This is a port of my original ZopeTree
product for Zope2, which was meant to replace the inflexible and
irreliable ZTUtils.Tree. This version for Zope 3 is released under the ZPL
and now added to the main distribution on people's request.

See README.txt for more infos.


=== Added File Zope3/src/zope/products/statictree/tests/__init__.py ===
# make this directory a package


=== Added File Zope3/src/zope/products/statictree/tests/basetest.py ===
##############################################################################
#
# Copyright (c) 2004 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: basetest.py,v 1.1 2004/01/16 12:39:04 philikon Exp $
"""

import unittest
from zope.interface import implements, Interface, Attribute
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app.tests import ztapi

from zope.products.statictree.interfaces import IUniqueId, \
     IChildObjects, ITreeStateEncoder
from zope.products.statictree.node import Node
from zope.products.statictree.utils import TreeStateEncoder

__metaclass__ = type

class IItem(Interface):
    """Simple object that can have an id and a set of children
    """
    id = Attribute("id")
    children = Attribute("children")

class Item:
    implements(IItem)

    def __init__(self, id, children=[]):
        self.id = id
        self.children = children

class ItemUniqueId:
    """Simplistic adapter from IItem to IUniqueId
    """
    implements(IUniqueId)

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

    def getId(self):
        return self.id

class ItemChildObjects:
    """Simplistic adapter from IItem to IChildObjects
    """
    implements(IChildObjects)

    def __init__(self, context):
        self.children = context.children

    def getChildObjects(self):
        return self.children

    def hasChildren(self):
        return len(self.children) > 0

# function used to convert a set of nested tuples to items and
# children items.
def make_item_from_tuple(item_tuple, dict):
    children = []
    if len(item_tuple) > 1:
        for child in item_tuple[1]:
            children.append(make_item_from_tuple(child, dict))
    item = Item(item_tuple[0], children)
    dict[item_tuple[0]] = item
    return item

tree = ('a', [
           ('b', [
               ('d',), ('e',)
               ]),
           ('c', [
               ('f', [
                   ('h',), ('i',)
                   ]),
               ('g')]
           ) ]
       )

class BaseTestCase(PlacelessSetup, unittest.TestCase):
    """Base class for most static tree tests
    """

    expanded_nodes = ['a', 'c']

    def setUp(self):
        super(BaseTestCase, self).setUp()
        # provide necessary components
        ztapi.provideAdapter(IItem, IUniqueId, ItemUniqueId)
        ztapi.provideAdapter(IItem, IChildObjects, ItemChildObjects)
        ztapi.provideUtility(ITreeStateEncoder, TreeStateEncoder())

    def makeItems(self):
        # this mapping will provide shortcuts to each object
        self.items = {}
        self.root_obj = make_item_from_tuple(tree, self.items)
        self.root_node = Node(self.root_obj, self.expanded_nodes)


=== Added File Zope3/src/zope/products/statictree/tests/test_adapters.py ===
##############################################################################
#
# Copyright (c) 2004 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_adapters.py,v 1.1 2004/01/16 12:39:04 philikon Exp $
"""

import unittest

from zope.interface import implements, directlyProvides
from zope.component.exceptions import ComponentLookupError

from zope.app.interfaces.location import ILocation
from zope.app.interfaces.container import IReadContainer
from zope.app.interfaces.services.service import ISite
from zope.app.interfaces.traversing import IContainmentRoot

from zope.app.container.sample import SampleContainer
from zope.app.container.contained import setitem
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.app import zapi
from zope.app.tests import ztapi

from zope.products.statictree.interfaces import IUniqueId, \
     IChildObjects, ITreeStateEncoder
from zope.products.statictree.utils import TreeStateEncoder
from zope.products.statictree.adapters import StubUniqueId, \
     StubChildObjects, LocationUniqueId, ContainerChildObjects, \
     ContainerSiteChildObjects

__metaclass__ = type

class SampleContent:
    pass

class SampleSite(SampleContainer):
    implements(ISite)

    def setSiteManager(self, sm):
        self._sm = sm

    def getSiteManager(self):
        try:
            return self._sm
        except AttributeError:
            raise ComponentLookupError

class AdapterTestCase(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(AdapterTestCase, self).setUp()
        # provide necessary components
        ztapi.provideAdapter(None, IUniqueId, StubUniqueId)
        ztapi.provideAdapter(None, IChildObjects, StubChildObjects)
        ztapi.provideAdapter(ILocation, IUniqueId, LocationUniqueId)
        ztapi.provideAdapter(IReadContainer, IChildObjects, ContainerChildObjects)
        ztapi.provideAdapter(ISite, IChildObjects, ContainerSiteChildObjects)
        ztapi.provideUtility(ITreeStateEncoder, TreeStateEncoder())
        self.makeObjects()

    def makeObjects(self):
        self.futurama = futurama = SampleSite()
        directlyProvides(futurama, IContainmentRoot)
        planetexpress = SampleContainer()
        robotfactory = SampleContainer()
        nimbus = SampleContainer()
        omicronpersei = SampleSite()

        bender = SampleContent()
        fry = SampleContent()
        leela = SampleContent()
        mom = SampleContent()
        zapp = SampleContent()
        kif = SampleContent()

        setitem(futurama, futurama.__setitem__, 'planetexpress', planetexpress)
        setitem(futurama, futurama.__setitem__, 'robotfactory', robotfactory)
        setitem(futurama, futurama.__setitem__, 'nimbus', nimbus)
        setitem(futurama, futurama.__setitem__, 'omicronpersei', omicronpersei)

        setitem(planetexpress, planetexpress.__setitem__, 'bender', bender)
        setitem(planetexpress, planetexpress.__setitem__, 'fry', fry)
        setitem(planetexpress, planetexpress.__setitem__, 'leela', leela)
        setitem(robotfactory, robotfactory.__setitem__, 'mom', mom)
        setitem(nimbus, nimbus.__setitem__, 'zapp', zapp)
        setitem(nimbus, nimbus.__setitem__, 'kif', kif)

    def test_stub_adapters(self):
        # test content unique id
        farnesworth = SampleContent()
        elzar = SampleContent()
        adapter = zapi.getAdapter(farnesworth, IUniqueId)
        adapter2 = zapi.getAdapter(elzar, IUniqueId)
        self.failIf(adapter.getId() == 'farnesworth')
        self.failIf(adapter2.getId() == 'elzar')
        # test for uniqueness
        self.failIf(adapter.getId() == adapter2.getId())

        # test content child objects
        adapter = zapi.getAdapter(elzar, IChildObjects)
        self.failIf(adapter.hasChildren())
        self.assert_(len(adapter.getChildObjects()) == 0)
        # test with acquired content
        bender = self.futurama['planetexpress']['bender']
        adapter = zapi.getAdapter(bender, IChildObjects)
        self.failIf(adapter.hasChildren())
        self.assert_(len(adapter.getChildObjects()) == 0)

    def test_location_uniqueid(self):
        # futurama does not have a name
        futurama = self.futurama
        adapter = zapi.getAdapter(futurama, IUniqueId)
        self.assertEqual(adapter.getId(), str(id(futurama)))

        # test container
        planetexpress = self.futurama['planetexpress']
        adapter = zapi.getAdapter(planetexpress, IUniqueId)
        self.assertEqual(adapter.getId(), 'planetexpress')

        # test content
        bender = self.futurama['planetexpress']['bender']
        adapter = zapi.getAdapter(bender, IUniqueId)
        self.assertEqual(adapter.getId(), r'bender\planetexpress')

    def test_container_childobjects(self):
        # test container with children
        futurama = self.futurama
        adapter = zapi.getAdapter(futurama, IChildObjects)
        self.assert_(adapter.hasChildren())
        self.assertEqual(adapter.getChildObjects(), futurama.values())

        # test acquired container with children
        planetexpress = self.futurama['planetexpress']
        adapter = zapi.getAdapter(planetexpress, IChildObjects)
        self.assert_(adapter.hasChildren())
        self.assertEqual(adapter.getChildObjects(), planetexpress.values())

        # test acquired container w/o children
        omicronpersei = self.futurama['omicronpersei']
        adapter = zapi.getAdapter(omicronpersei, IChildObjects)
        self.failIf(adapter.hasChildren())
        self.assertEqual(adapter.getChildObjects(), [])

    def test_container_site(self):
        sm = object()
        futurama = self.futurama
        omicronpersei = self.futurama['omicronpersei']

        # test behaviour before and after setting a site
        adapter = zapi.getAdapter(futurama, IChildObjects)
        self.assert_(adapter.hasChildren())
        self.assertEqual(adapter.getChildObjects(), futurama.values())
        futurama.setSiteManager(sm)
        self.assert_(sm in adapter.getChildObjects())

        adapter = zapi.getAdapter(omicronpersei, IChildObjects)
        self.failIf(adapter.hasChildren())
        omicronpersei.setSiteManager(sm)
        self.assert_(adapter.hasChildren())
        self.assertEqual(adapter.getChildObjects(), [sm])

def test_suite():
    return unittest.makeSuite(AdapterTestCase)

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


=== Added File Zope3/src/zope/products/statictree/tests/test_browser.py ===
##############################################################################
#
# Copyright (c) 2004 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_browser.py,v 1.1 2004/01/16 12:39:04 philikon Exp $
"""

import unittest
from zope.publisher.browser import TestRequest
from zope.app import zapi
from zope.app.tests import ztapi

from zope.products.statictree.utils import TreeStateEncoder
from zope.products.statictree.browser import StaticTreeView

from basetest import BaseTestCase

class BrowserTestCase(BaseTestCase):

    def setUp(self):
        super(BrowserTestCase, self).setUp()
        self.makeItems()
        # provide the view for all objects (None)
        ztapi.browserView(None, 'static_cookie_tree', [StaticTreeView])

    def makeRequest(self):
        request = self.request = TestRequest()

    def makeRequestWithVar(self):
        varname = StaticTreeView.request_variable 
        encoder = TreeStateEncoder()
        tree_state = encoder.encodeTreeState(self.expanded_nodes)
        environ = {varname: tree_state}
        request = TestRequest(environ=environ)
        return request

    def test_cookie_tree_pre_expanded(self):
        request = self.makeRequestWithVar()
        view = zapi.getView(self.root_obj, 'static_cookie_tree', request)
        cookie_tree = view.cookieTree()
        self.assert_(self.root_node.expanded)
        for node in self.root_node.getFlatNodes():
            self.assertEqual(node.expanded, node.getId() in self.expanded_nodes)

    def test_cookie_tree_sets_cookie(self):
        request = self.makeRequestWithVar()
        view = zapi.getView(self.root_obj, 'static_cookie_tree', request)
        cookie_tree = view.cookieTree()
        self.failIf(request.response.getCookie(view.request_variable) is None)

def test_suite():
    return unittest.makeSuite(BrowserTestCase)

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


=== Added File Zope3/src/zope/products/statictree/tests/test_encoder.py ===
##############################################################################
#
# Copyright (c) 2004 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_encoder.py,v 1.1 2004/01/16 12:39:04 philikon Exp $
"""

import unittest
from zope.testing.doctestunit import DocTestSuite

def test_suite():
    return unittest.TestSuite((
        DocTestSuite('zope.products.statictree.utils'),
        ))

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


=== Added File Zope3/src/zope/products/statictree/tests/test_filters.py ===
##############################################################################
#
# Copyright (c) 2004 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_filters.py,v 1.1 2004/01/16 12:39:04 philikon Exp $
"""

import unittest

from zope.interface import implements, directlyProvides
from zope.interface.interface import InterfaceClass
from zope.app import zapi

from zope.products.statictree.filters import OnlyInterfacesFilter, \
     AllButInterfacesFilter

from test_adapters import SampleContent

__metaclass__ = type

IRobot = InterfaceClass('IRobot', (), {})
IHuman = InterfaceClass('IHuman', (), {})
IAlien = InterfaceClass('IAlien', (), {})
ISpaceShipCaptain = InterfaceClass('ISpaceShipCaptain', (), {})
IDeliveryBoy = InterfaceClass('IDeliveryBoy', (IHuman,), {})
IProfessor = InterfaceClass('IProfessor', (IHuman,), {})

class FilterTestCase(unittest.TestCase):

    def setUp(self):
        self.makeObjects()

    def makeObjects(self):
        to_be_made = {
            'bender':      IRobot,
            'fry':         IDeliveryBoy,
            'farnesworth': IProfessor,
            'zapp':        (IHuman, ISpaceShipCaptain),
            'lur':         (IAlien, ISpaceShipCaptain),
            'kif':         IAlien,
            }
        self.items = items = {}
        for name, iface in to_be_made.items():
            items[name] = obj = SampleContent()
            directlyProvides(obj, iface)

    def filterAndCompare(self, filter, expected):
        items = self.items
        result = [name for name, obj in items.items()
                  if filter.matches(obj)]
        for name in expected:
            if name not in result:
                return False
            result.remove(name)
        if len(result):
            return False
        return True

    def test_only_interfaces_filter(self):
        filter = OnlyInterfacesFilter(IHuman)
        self.assert_(self.filterAndCompare(filter, ('fry', 'farnesworth', 'zapp')))

        # even if we add delivery boy to it, the list shouldn't change
        filter = OnlyInterfacesFilter(IHuman, IDeliveryBoy)
        self.assert_(self.filterAndCompare(filter, ('fry', 'farnesworth', 'zapp')))

        # Lur from Omicron Persei 8 is a starship captain too
        # (he also likes to eating hippies and destroying earth)
        filter = OnlyInterfacesFilter(IHuman, ISpaceShipCaptain)
        self.assert_(self.filterAndCompare(filter, ('fry', 'farnesworth', 'zapp', 'lur')))

    def test_all_but_interfaces_filter(self):
        # "death to all humans!"
        filter = AllButInterfacesFilter(IHuman)
        self.assert_(self.filterAndCompare(filter, ('lur', 'kif', 'bender')))

        # and to all spaceship captains...
        filter = AllButInterfacesFilter(IHuman, ISpaceShipCaptain)
        self.assert_(self.filterAndCompare(filter, ('kif', 'bender')))

def test_suite():
    return unittest.makeSuite(FilterTestCase)

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


=== Added File Zope3/src/zope/products/statictree/tests/test_node.py ===
##############################################################################
#
# Copyright (c) 2004 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_node.py,v 1.1 2004/01/16 12:39:04 philikon Exp $
"""

import unittest
from basetest import BaseTestCase
from zope.interface import implements
from zope.app.interfaces.find import IObjectFindFilter
from zope.products.statictree.node import Node

class FilterByObject:
    """Simple filter that filters out any objects that wasn't passed
    in as a valid object before
    """
    implements(IObjectFindFilter)

    def __init__(self, *objects):
        self.objects = objects

    def match(self, obj):
        return obj in self.objects

class NodeTestCase(BaseTestCase):

    def setUp(self):
        super(NodeTestCase, self).setUp()
        self.makeItems()

    def test_expand_collapse(self):
        # first the node is expanded
        root_node = self.root_node
        self.failUnless(root_node.expanded)
        # now collapse it
        root_node.collapse()
        self.failIf(root_node.expanded)
        # make sure there are no children nodes returned!
        self.assertEqual(root_node.getChildNodes(), [])
        # expand it again
        root_node.expand()
        self.failUnless(root_node.expanded)

    def test_children(self):
        # test hasChildren()
        root_node = self.root_node
        self.failUnless(root_node.hasChildren())
        
        # test getChildNodes()
        children = [node.context for node in root_node.getChildNodes()]
        expected = [self.items['b'], self.items['c']]
        self.assertEqual(children, expected)

        # test with filter
        expand_all = self.items.keys() # expand all nodes
        # emulate node expansion with the FilterByObject filter
        filter = FilterByObject([self.items[id] for id in self.expanded_nodes])
        filtered_root = Node(self.root_obj, expand_all, filter)
        children = [node.context for node in root_node.getChildNodes()]
        expected = [self.items['b'], self.items['c']]
        self.assertEqual(children, expected)

    def test_flat(self):
        # test getFlatNodes()
        root_node = self.root_node
        flat = root_node.getFlatNodes()
        children = [node.context for node in flat]
        # 'a' is not expected because the node on which getFlatNodes()
        # is called is not in the list
        expected = [self.items[i] for i in "bcfg"]
        self.assertEqual(children, expected)

    def test_pre_expanded(self):
        # 'a' is not expected because the node on which getFlatNodes()
        # is called is not in the list
        expected = [self.items[i] for i in "bcfg"]
        # test against to getFlatNodes()
        flat = [node.context for node in self.root_node.getFlatNodes()]
        self.assertEqual(flat, expected)

    def test_flat_dicts(self):
        flat, maxdepth = self.root_node.getFlatDicts()
        self.assertEqual(maxdepth, 2)
        self.assertEqual(len(flat), len(self.root_node.getFlatNodes()))
        bdict = flat[0]
        node = bdict['node']
        self.assertEqual(bdict['depth'], 0)
        self.assertEqual(node.getId(), 'b')
        self.assert_(node.hasChildren())
        self.assert_(node.context is self.items['b'])

    def test_depth(self):
        expanded = ['a', 'c', 'f']
        root_node = Node(self.root_obj, expanded)
        flat, maxdepth = root_node.getFlatDicts()

def test_suite():
    return unittest.makeSuite(NodeTestCase)

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




More information about the Zope3-Checkins mailing list