[Zope3-checkins] CVS: Zope3/src/zope/app/publication/tests - __init__.py:1.1.2.1 test_simplecomponenttraverser.py:1.1.2.1 test_zopepublication.py:1.1.2.1

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


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

Added Files:
      Tag: NameGeddon-branch
	__init__.py test_simplecomponenttraverser.py 
	test_zopepublication.py 
Log Message:
Initial renaming before debugging

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


=== Added File Zope3/src/zope/app/publication/tests/test_simplecomponenttraverser.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_simplecomponenttraverser.py,v 1.1.2.1 2002/12/23 19:32:01 jim Exp $
"""

import unittest, sys
from zope.component.tests.request import Request
from zope.app.publication.traversers import SimpleComponentTraverser
from zope.component import getService
from zope.interface import Interface
from zope.exceptions import NotFoundError
from zope.app.tests.placelesssetup import PlacelessSetup

class I(Interface):
    pass


class Container:
    def __init__(self, **kw):
        for k in kw:
            setattr(self, k , kw[k])

    def get(self, name, default=None):
        return getattr(self, name, default)


class Request(Request):
    def getEffectiveURL(self):
        return ''


class View:
    def __init__(self, comp, request):
        self._comp = comp


class Test(PlacelessSetup, unittest.TestCase):
    def testAttr(self):
        # test container traver
        foo = Container()
        c   = Container( foo=foo )
        req = Request( I, '')

        T = SimpleComponentTraverser(c, req)

        self.assertRaises(NotFoundError , T.publishTraverse, req ,'foo')


    def testView(self):
        # test getting a view
        foo = Container()
        c   = Container( foo=foo )
        req = Request( I, '')

        T = SimpleComponentTraverser(c, req)
        getService(None,"Views").provideView(None , 'foo', I, [View])

        self.failUnless(T.publishTraverse(req,'foo').__class__ is View )

        self.assertRaises(NotFoundError , T.publishTraverse, req ,'morebar')



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


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


=== Added File Zope3/src/zope/app/publication/tests/test_zopepublication.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

from zope.interface import Interface

from zope.component import getService, getServiceManager

from zope.publisher.publish import publish
from zope.publisher.browser import TestRequest
from zope.publisher.browser import BrowserView
from zope.publisher.interfaces.browser import IBrowserPublisher
from zope.publisher.interfaces.browser import IBrowserPresentation

from zope.proxy.context.context import getWrapperContext
from zope.proxy.introspection import removeAllProxies

from zope.security.checker import defineChecker, NamesChecker

from zope.proxy.context import wrapperTypes

from zope.app.security.registries.principalregistry import principalRegistry
from zope.app.security.grants.global.principalrolemanager \
     import principalRoleManager

from zope.app.publication.zopepublication import ZopePublication
from zope.app.publication.browser import BrowserPublication
from zope.app.publication.traversers import TestTraverser


def foo():
    " "
    return '<html><body>hello base fans</body></html>'

class DummyPublished:

    __implements__ = IBrowserPublisher

    def publishTraverse(self, request, name):
        if name == 'bruce':
            return foo
        raise KeyError, name

    def browserDefault(self, request):
        return self, ['bruce']

class DummyView(DummyPublished, BrowserView):

    __implements__ = DummyPublished.__implements__, BrowserView.__implements__


class BasePublicationTests(BasePublicationTests_):

    def _createRequest(self, path, publication, **kw):
        request = TestRequest(PATH_INFO=path, **kw)
        request.setPublication(publication)
        return request


class BrowserDefaultTests(BasePublicationTests):
    """
    test browser default

    many views lead to a default view
    <base href="/somepath/@@view/view_method">

    """
    klass = BrowserPublication

    def testBaseTagNoBase(self):
        self._testBaseTags('/somepath/@@view/', '')

    def testBaseTag1(self):
        self._testBaseTags('/somepath/@@view',
                           'http://127.0.0.1/somepath/@@view/bruce')

    def testBaseTag2(self):
        self._testBaseTags('/somepath/',
                           'http://127.0.0.1/somepath/@@view/bruce')

    def testBaseTag3(self):
        self._testBaseTags('/somepath',
                           'http://127.0.0.1/somepath/@@view/bruce')



    def _testBaseTags(self, url, expected):

        class I1(Interface): pass

        from persistence import Persistent

        class O1(Persistent):
            __implements__ = I1


        pub = BrowserPublication(self.db)

        getService(None,'Views').provideView(I1, 'view',
                           IBrowserPresentation, [DummyView])
        getService(None,'Views').setDefaultViewName(I1,
                             IBrowserPresentation, 'view')
        getService(None, 'Views').provideView(None,
                    '_traverse', IBrowserPresentation, [TestTraverser])

        ob = O1()

        ## the following is for running the tests standalone
        principalRegistry.defineDefaultPrincipal(
            'tim', 'timbot', 'ai at its best')

        principalRoleManager.assignRoleToPrincipal('Manager', 'tim')


        # now place our object inside the application
        from transaction import get_transaction

        connection = self.db.open()
        app = connection.root()['Application']
        app.somepath = ob
        get_transaction().commit()
        connection.close()

        defineChecker(app.__class__, NamesChecker(somepath='xxx'))

        req = self._createRequest(url, pub)
        response = req.response

        publish(req, handle_errors=0)

        self.assertEqual(response.getBase(), expected)


    def _createRequest(self, path, publication, **kw):
        request = TestRequest(PATH_INFO=path, **kw)
        request.setPublication(publication)
        return request



class SimpleObject:
    def __init__(self, v):
        self.v = v

class I1(Interface):
    pass

class mydict(dict):
    __implements__ = I1


class BrowserPublicationTests(BasePublicationTests):

    klass = BrowserPublication

    def testNativeTraverseNameWrapping(self):
        pub = self.klass(self.db)
        ob = DummyPublished()
        ob2 = pub.traverseName(self._createRequest('/bruce',pub), ob, 'bruce')
        self.failUnless(ob2 is not ob)
        self.failUnless(type(ob2) in wrapperTypes)

    def testAdaptedTraverseNameWrapping(self):

        class Adapter:
            " "
            __implements__ = IBrowserPublisher
            def __init__(self, context, request):
                self.context = context
                self.counter = 0

            def publishTraverse(self, request, name):
                self.counter+=1
                return self.context[name]

        provideView=getService(None, "Views").provideView
        provideView(I1, '_traverse', IBrowserPresentation, [Adapter])
        ob = mydict()
        ob['bruce'] =  SimpleObject('bruce')
        ob['bruce2'] =  SimpleObject('bruce2')
        pub = self.klass(self.db)
        ob2 = pub.traverseName(self._createRequest('/bruce',pub), ob, 'bruce')
        self.failUnless(type(ob2) in wrapperTypes)
        unw = removeAllProxies(ob2)
        self.assertEqual(unw.v, 'bruce')

    def testAdaptedTraverseDefaultWrapping(self):
        # Test default content and make sure that it's wrapped.
        class Adapter:
            __implements__ = IBrowserPublisher
            def __init__(self, context, request):
                self.context = context

            def browserDefault(self, request):
                return (self.context['bruce'], 'dummy')

        provideView=getService(None, "Views").provideView
        provideView(I1, '_traverse', IBrowserPresentation, [Adapter])
        ob = mydict()
        ob['bruce'] =  SimpleObject('bruce')
        ob['bruce2'] =  SimpleObject('bruce2')
        pub = self.klass(self.db)
        ob2, x = pub.getDefaultTraversal(self._createRequest('/bruce',pub), ob)
        self.assertEqual(x, 'dummy')
        self.failUnless(type(ob2) in wrapperTypes)
        unw = removeAllProxies(ob2)
        self.assertEqual(unw.v, 'bruce')


    # XXX we no longer support path parameters! (At least for now)
    def XXXtestTraverseSkinExtraction(self):
        class I1(Interface): pass
        class C: __implements__ = I1
        class BobView(DummyView): pass

        pub = self.klass(self.db)
        ob = C()
        provideView=getService(None, "Views").provideView
        provideView(I1, 'edit', IBrowserPresentation, [BobView])

        r = self._createRequest('/@@edit;skin=zmi',pub)
        ob2 = pub.traverseName(r , ob, '@@edit;skin=zmi')
        self.assertEqual(r.getPresentationSkin(), 'zmi')
        self.assertEqual(ob2.__class__ , BobView)

        r = self._createRequest('/@@edit;skin=zmi',pub)
        ob2 = pub.traverseName(r , ob, '@@edit;skin=zmi')
        self.assertEqual(r.getPresentationSkin(), 'zmi')
        self.assertEqual(ob2.__class__ , BobView)

    def testTraverseName(self):
        pub = self.klass(self.db)
        class C:
            x = SimpleObject(1)
        ob = C()
        r = self._createRequest('/x',pub)
        provideView=getService(None, "Views").provideView
        provideView(None, '_traverse', IBrowserPresentation, [TestTraverser])
        ob2 = pub.traverseName(r, ob, 'x')
        self.assertEqual(removeAllProxies(ob2).v, 1)
        self.assertEqual(getWrapperContext(ob2), ob)

    def testTraverseNameView(self):
        pub = self.klass(self.db)
        class I(Interface): pass
        class C:
            __implements__ = I
        ob = C()
        class V:
            def __init__(self, context, request): pass
            __implements__ = IBrowserPresentation
        r = self._createRequest('/@@spam',pub)
        provideView=getService(None, "Views").provideView
        provideView(I, 'spam', IBrowserPresentation, [V])
        ob2 = pub.traverseName(r, ob, '@@spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
        self.assertEqual(getWrapperContext(ob2), ob)

    def testTraverseNameServices(self):
        pub = self.klass(self.db)
        class C:
            def getServiceManager(self):
                return SimpleObject(1)
        ob = C()
        r = self._createRequest('/++etc++Services',pub)
        ob2 = pub.traverseName(r, ob, '++etc++Services')
        self.assertEqual(removeAllProxies(ob2).v, 1)
        self.assertEqual(getWrapperContext(ob2), ob)

    def testTraverseNameApplicationControl(self):
        from zope.app.applicationcontrol.applicationcontrol \
             import applicationController, applicationControllerRoot
        pub = self.klass(self.db)
        r = self._createRequest('/++etc++ApplicationController',pub)
        ac = pub.traverseName(r,
                              applicationControllerRoot,
                              '++etc++ApplicationController')
        self.assertEqual(ac, applicationController)
        r = self._createRequest('/++etc++ApplicationController',pub)
        app = r.publication.getApplication(r)
        self.assertEqual(app, applicationControllerRoot)


def test_suite():
    t2 = unittest.makeSuite(BrowserPublicationTests, 'test')
    t3 = unittest.makeSuite(BrowserDefaultTests, 'test')
    return unittest.TestSuite((t2, t3))


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


import unittest

from zope.interface.verify import verifyClass
from zope.interface.implements import instancesOfObjectImplements

from zodb.storage.mapping import DB

from zope.app.tests.placelesssetup import PlacelessSetup
from zope.component.adapter import provideAdapter 

from zope.interfaces.i18n import IUserPreferredCharsets

from zope.publisher.base import TestPublication
from zope.publisher.http import IHTTPRequest
from zope.publisher.http import HTTPCharsets

from Zope.Security import SimpleSecurityPolicies
from zope.security.securitymanagement import setSecurityPolicy

from zope.app.security.registries.principalregistry import principalRegistry
from zope.app.interfaces.security \
     import IUnauthenticatedPrincipal

from zope.app.publication.zopepublication import ZopePublication

from zope.app.content.folder import Folder
from zope.app.content.folder import RootFolder

from zope.component.interfaces import IServiceService

from zope.publisher.base import TestRequest

from zope.component.service import serviceManager

from transaction import get_transaction

class BasePublicationTests(PlacelessSetup, unittest.TestCase):
    klass = ZopePublication 
    
    def setUp(self):
        PlacelessSetup.setUp(self)
        provideAdapter(IHTTPRequest, IUserPreferredCharsets, HTTPCharsets)    
        self.policy = setSecurityPolicy(
            SimpleSecurityPolicies.PermissiveSecurityPolicy()
            )
        self.db = DB("foo")

        connection = self.db.open()
        root = connection.root()
        app = getattr(root, ZopePublication.root_name, None)

        if app is None:
            from zope.app.content.folder import RootFolder

            app = RootFolder()
            root[ZopePublication.root_name] = app

            get_transaction().commit()

        connection.close()
        
        from zope.app.traversing.namespaces import provideNamespaceHandler
        from zope.app.traversing.presentationnamespaces import view, resource
        from zope.app.traversing.etcnamespace import etc
        provideNamespaceHandler('view', view)
        provideNamespaceHandler('resource', resource)
        provideNamespaceHandler('etc', etc)

    def tearDown(self):
        setSecurityPolicy(self.policy) # XXX still needed?
        PlacelessSetup.tearDown(self)

    def testInterfacesVerify(self):
        for interface in instancesOfObjectImplements(self.klass):
            verifyClass(interface, TestPublication)

class Principal:
    def __init__(self, id): self._id = id
    def getId(self): return self._id
    def getTitle(self): return ''
    def getDescription(self): return ''

class UnauthenticatedPrincipal(Principal):
    __implements__ = IUnauthenticatedPrincipal


class AuthService1:

    def authenticate(self, request):
        return None

    def unauthenticatedPrincipal(self):
        return UnauthenticatedPrincipal('test.anonymous')

    def unauthorized(self, id, request):
        pass

    def getPrincipal(self, id):
        return UnauthenticatedPrincipal(id)
        

class AuthService2(AuthService1):

    def authenticate(self, request):
        return Principal('test.bob')

    def getPrincipal(self, id):
        return Principal(id)
        

class ServiceManager:

    __implements__ = IServiceService # a dirty lie
    
    def __init__(self, auth):   self.auth = auth
    def get(self, key, d=None):      return self.auth
    __getitem__ = get
    def __contains__(self, key): return 1

    def getService(self, name):
        # I just wanna get the test to pass. Waaaaa
        return serviceManager.getService(name)


class ZopePublicationTests(BasePublicationTests):
    klass = ZopePublication

    def testPlacefulAuth(self):
        principalRegistry.defineDefaultPrincipal('anonymous', '')
        
        root = self.db.open().root()
        app = root[ZopePublication.root_name]
        app.setObject('f1', Folder())
        f1 = app['f1']
        f1.setObject('f2', Folder())
        f1.setServiceManager(ServiceManager(AuthService1()))
        f2 = f1['f2']
        f2.setServiceManager(ServiceManager(AuthService2()))
        get_transaction().commit()

        request = TestRequest('/f1/f2')

        from zope.component.view import provideView
        from zope.app.interfaces.container import ISimpleReadContainer
        from zope.app.container.traversal \
             import ContainerTraverser
        from zope.component.interfaces import IPresentation
        provideView(ISimpleReadContainer, '_traverse', IPresentation,
                    ContainerTraverser)

        from zope.app.content.folder import IFolder
        from zope.security.checker import defineChecker, InterfaceChecker
        defineChecker(Folder, InterfaceChecker(IFolder))
        defineChecker(RootFolder, InterfaceChecker(IFolder))

        request.setViewType(IPresentation)

        publication = self.klass(self.db)

        publication.beforeTraversal(request)
        self.assertEqual(request.user.getId(), 'anonymous')
        root = publication.getApplication(request)
        publication.callTraversalHooks(request, root)
        self.assertEqual(request.user.getId(), 'anonymous')
        ob = publication.traverseName(request, root, 'f1')
        publication.callTraversalHooks(request, ob)
        self.assertEqual(request.user.getId(), 'test.anonymous')
        ob = publication.traverseName(request, ob, 'f2')
        publication.afterTraversal(request, ob)
        self.assertEqual(request.user.getId(), 'test.bob')
        
def test_suite():
    return unittest.makeSuite(ZopePublicationTests, 'test')

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