Exemplo n.º 1
0
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass
            implements(IXMLRPCPresentation)


        # Register the simple traverser so we can traverse without @@
        from zope.publisher.interfaces.xmlrpc import IXMLRPCPublisher
        from zope.publisher.interfaces.xmlrpc import IXMLRPCRequest
        from zope.app.publication.traversers import SimpleComponentTraverser
        ztapi.provideView(Interface, IXMLRPCRequest, IXMLRPCPublisher, '',
                          SimpleComponentTraverser)

        r = self._createRequest('/@@spam', pub)
        ztapi.provideView(I, IXMLRPCRequest, Interface, 'spam', V)
        ob2 = pub.traverseName(r, ob, '@@spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
        
        ob2 = pub.traverseName(r, ob, 'spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
Exemplo n.º 2
0
    def testNoViewOnClassicClassException(self):
        from zope.interface import Interface
        from types import ClassType

        class ClassicError:
            __metaclass__ = ClassType

        class IClassicError(Interface):
            pass

        classImplements(ClassicError, IClassicError)
        ztapi.setDefaultViewName(IClassicError, 'name', self.presentation_type)
        view_text = 'You made a classic error ;-)'
        ztapi.provideView(IClassicError, self.presentation_type, Interface,
                          'name', lambda obj, request: lambda: view_text)
        try:
            raise ClassicError
        except:
            pass
        self.publication.handleException(self.object,
                                         self.request,
                                         sys.exc_info(),
                                         retry_allowed=False)
        # check we don't get the view we registered
        self.failIf(''.join(self.request.response._result) == view_text)
        # check we do actually get something
        self.failIf(''.join(self.request.response._result) == '')
Exemplo n.º 3
0
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass

            implements(IXMLRPCPresentation)

        # Register the simple traverser so we can traverse without @@
        ztapi.provideView(Interface, IXMLRPCRequest, IXMLRPCPublisher, '',
                          SimpleComponentTraverser)

        r = self._createRequest('/@@spam', pub)
        ztapi.provideView(I, IXMLRPCRequest, Interface, 'spam', V)
        ob2 = pub.traverseName(r, ob, '@@spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)

        ob2 = pub.traverseName(r, ob, 'spam')
        self.assertEqual(removeAllProxies(ob2).__class__, V)
    def testTraverseNameView(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

        ob = C()

        class V(object):
            def __init__(self, context, request):
                pass

            implements(ISOAPPresentation)

        # Register the simple traverser so we can traverse without @@
        from z3c.soap.interfaces import ISOAPPublisher, ISOAPRequest
        from zope.app.publication.traversers import SimpleComponentTraverser

        ztapi.provideView(Interface, ISOAPRequest, ISOAPPublisher, "", SimpleComponentTraverser)

        r = self._createRequest("/@@spam", pub)
        ztapi.provideView(I, ISOAPRequest, Interface, "spam", V)
        ob2 = pub.traverseName(r, ob, "@@spam")
        self.assertEqual(removeAllProxies(ob2).__class__, V)

        ob2 = pub.traverseName(r, ob, "spam")
        self.assertEqual(removeAllProxies(ob2).__class__, V)
Exemplo n.º 5
0
def setUp(test):
    test.globs['rootFolder'] = setup.placefulSetUp(True)

    class RootModule(str):
        implements(IAPIDocRootModule)
    ztapi.provideUtility(IAPIDocRootModule, RootModule('zope'), "zope")

    module = CodeModule()
    module.__name__ = ''
    directlyProvides(module, IContainmentRoot)
    ztapi.provideUtility(IDocumentationModule, module, "Code")

    module = ZCMLModule()
    module.__name__ = ''
    directlyProvides(module, IContainmentRoot)
    ztapi.provideUtility(IDocumentationModule, module, "ZCML")

    # Register Renderer Components
    ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory,
                         'zope.source.rest')
    ztapi.browserView(IReStructuredTextSource, '',
                      ReStructuredTextToHTMLRenderer)
    # Cheat and register the ReST factory for STX as well.
    ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory,
                         'zope.source.stx')

    # Register ++apidoc++ namespace
    from zope.app.apidoc.apidoc import apidocNamespace
    from zope.app.traversing.interfaces import ITraversable
    ztapi.provideAdapter(None, ITraversable, apidocNamespace, name="apidoc")
    ztapi.provideView(None, None, ITraversable, "apidoc", apidocNamespace)

    # Register ++apidoc++ namespace
    from zope.app.traversing.namespace import view
    from zope.app.traversing.interfaces import ITraversable
    ztapi.provideAdapter(None, ITraversable, view, name="view")
    ztapi.provideView(None, None, ITraversable, "view", view)

    context = xmlconfig.string(meta)

    # Fix up path for tests.
    global old_context
    old_context = zope.app.appsetup.appsetup.__config_context
    zope.app.appsetup.appsetup.__config_context = context

    # Fix up path for tests.
    global old_source_file
    old_source_file = zope.app.appsetup.appsetup.__config_source
    zope.app.appsetup.appsetup.__config_source = os.path.join(
        os.path.dirname(zope.app.__file__), 'meta.zcml')

    # Register the index.html view for codemodule.class_.Class
    from zope.app.apidoc.codemodule.class_ import Class
    from zope.app.apidoc.codemodule.browser.class_ import ClassDetails
    from zope.app.publisher.browser import BrowserView
    class Details(ClassDetails, BrowserView):
        pass
    ztapi.browserView(Class, 'index.html', Details)
Exemplo n.º 6
0
    def test_callObject(self):
        pub = zope.app.publication.http.HTTPPublication(None)
        request = HTTPRequest(StringIO(''), {})
        request.method = 'SPAM'

        ztapi.provideView(I, IHTTPRequest, Interface, 'SPAM', V)

        ob = C()
        pub.callObject(request, ob)
        self.assertEqual(ob.spammed, 1)
Exemplo n.º 7
0
 def testTraverseName(self):
     pub = self.klass(self.db)
     class C(object):
         x = SimpleObject(1)
     ob = C()
     r = self._createRequest('/x', pub)
     ztapi.provideView(None, IXMLRPCRequest, IXMLRPCPublisher,
                       '', TestTraverser)
     ob2 = pub.traverseName(r, ob, 'x')
     self.assertEqual(removeAllProxies(ob2).v, 1)
Exemplo n.º 8
0
    def test_callObject(self):
        pub = zope.app.publication.http.HTTPPublication(None)
        request = HTTPRequest(StringIO(''), {})
        request.method = 'SPAM'

        ztapi.provideView(I, IHTTPRequest, Interface, 'SPAM', V)

        ob = C()
        pub.callObject(request, ob)
        self.assertEqual(ob.spammed, 1)
    def testTraverseName(self):
        pub = self.klass(self.db)

        class C(object):
            x = SimpleObject(1)

        ob = C()
        r = self._createRequest("/x", pub)
        ztapi.provideView(None, ISOAPRequest, ISOAPPublisher, "", TestTraverser)
        ob2 = pub.traverseName(r, ob, "x")
        self.assertEqual(removeAllProxies(ob2).v, 1)
    def testView(self):
        # test getting a view
        foo = Container()
        c   = Container(foo=foo)
        req = Request(I)

        T = SimpleComponentTraverser(c, req)
        ztapi.provideView(None, I, Interface, 'foo', View)

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

        self.assertRaises(NotFound, T.publishTraverse, req , 'morebar')
Exemplo n.º 11
0
    def testTraverseName(self):
        pub = self.klass(self.db)

        class C(object):
            x = SimpleObject(1)

        ob = C()
        r = self._createRequest('/x', pub)
        ztapi.provideView(None, IXMLRPCRequest, IXMLRPCPublisher, '',
                          TestTraverser)
        ob2 = pub.traverseName(r, ob, 'x')
        self.assertEqual(removeAllProxies(ob2).v, 1)
Exemplo n.º 12
0
    def testView(self):
        # test getting a view
        foo = Container()
        c   = Container(foo=foo)
        req = Request(I)

        T = SimpleComponentTraverser(c, req)
        ztapi.provideView(None, I, Interface, 'foo', View)

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

        self.assertRaises(NotFound, T.publishTraverse, req , 'morebar')
Exemplo n.º 13
0
def setUp(test):
    setup.placefulSetUp()

    # resource namespace setup
    from zope.app.traversing.interfaces import ITraversable
    from zope.app.traversing.namespace import resource
    ztapi.provideAdapter(None, ITraversable, resource, name="resource")
    ztapi.provideView(None, None, ITraversable, "resource", resource)

    from zope.app.pagetemplate import metaconfigure
    from zope.contentprovider import tales
    metaconfigure.registerType('provider', tales.TALESProviderExpression)

    zope.security.management.getInteraction().add(TestParticipation())
Exemplo n.º 14
0
def setUp(test=None):
    testing.setUp()
    from bibliograph.rendering.renderers.pdf import PdfRenderView
    from bibliograph.rendering.utility import ExternalTransformUtility
    ztapi.provideView(IBibliographicReference, None, None,
                      name=u'reference.bib',
                      factory=BibtexRenderView)
    ztapi.provideView(IBibliographicReference, None, None,
                      name=u'reference.pdf',
                      factory=PdfRenderView)

    ztapi.provideUtility(IBibTransformUtility, ExternalTransformUtility(),
                         name=u'external')
    ztapi.browserViewProviding(None, AbsoluteURL, IAbsoluteURL)
Exemplo n.º 15
0
 def setUp(self):
     from zope.publisher.interfaces.http import IHTTPRequest
     PlacelessSetup.setUp(self)
     ztapi.provideView(I, IHTTPRequest, Interface, 'GET', GetView)
     ztapi.provideView(I, IHTTPRequest, Interface, 'DELETE', DeleteView)
     ztapi.provideView(I, IHTTPRequest, Interface, 'irrelevant', GetView)
     ztapi.provideView(I, IHTTPRequest, Interface, 'also_irr.', DeleteView)
Exemplo n.º 16
0
 def setUp(self):
     from zope.publisher.interfaces.http import IHTTPRequest
     PlacelessSetup.setUp(self)
     ztapi.provideView(I, IHTTPRequest, Interface, 'GET', GetView)
     ztapi.provideView(I, IHTTPRequest, Interface, 'DELETE', DeleteView)
     ztapi.provideView(I, IHTTPRequest, Interface, 'irrelevant', GetView)
     ztapi.provideView(I, IHTTPRequest, Interface, 'also_irr.', DeleteView)
Exemplo n.º 17
0
    def testPlacefulAuth(self):
        setup.setUpTraversal()
        setup.setUpSiteManagerLookup()
        principalRegistry.defineDefaultPrincipal('anonymous', '')

        root = self.db.open().root()
        app = root[ZopePublication.root_name]
        app['f1'] = rootFolder()
        f1 = app['f1']
        f1['f2'] = Folder()
        sm1 = setup.createSiteManager(f1)
        setup.addUtility(sm1, '', IAuthenticationUtility, AuthUtility1())

        f2 = f1['f2']
        sm2 = setup.createSiteManager(f2)
        setup.addUtility(sm2, '', IAuthenticationUtility, AuthUtility2())
        transaction.commit()

        from zope.app.container.interfaces import ISimpleReadContainer
        from zope.app.container.traversal import ContainerTraverser

        ztapi.provideView(ISimpleReadContainer, IRequest, IPublishTraverse, '',
                          ContainerTraverser)

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

        self.publication.beforeTraversal(self.request)
        self.assertEqual(list(queryInteraction().participations),
                         [self.request])
        self.assertEqual(self.request.principal.id, 'anonymous')
        root = self.publication.getApplication(self.request)
        self.publication.callTraversalHooks(self.request, root)
        self.assertEqual(self.request.principal.id, 'anonymous')
        ob = self.publication.traverseName(self.request, root, 'f1')
        self.publication.callTraversalHooks(self.request, ob)
        self.assertEqual(self.request.principal.id, 'test.anonymous')
        ob = self.publication.traverseName(self.request, ob, 'f2')
        self.publication.afterTraversal(self.request, ob)
        self.assertEqual(self.request.principal.id, 'test.bob')
        self.assertEqual(list(queryInteraction().participations),
                         [self.request])
        self.publication.endRequest(self.request, ob)
        self.assertEqual(queryInteraction(), None)
Exemplo n.º 18
0
    def testPlacefulAuth(self):
        setup.setUpTraversal()
        setup.setUpSiteManagerLookup()
        principalRegistry.defineDefaultPrincipal('anonymous', '')

        root = self.db.open().root()
        app = root[ZopePublication.root_name]
        app['f1'] = rootFolder()
        f1 = app['f1']
        f1['f2'] = Folder()
        sm1 = setup.createSiteManager(f1)
        setup.addUtility(sm1, '', IAuthenticationUtility, AuthUtility1())

        f2 = f1['f2']
        sm2 = setup.createSiteManager(f2)
        setup.addUtility(sm2, '', IAuthenticationUtility, AuthUtility2())
        transaction.commit()

        from zope.app.container.interfaces import ISimpleReadContainer
        from zope.app.container.traversal import ContainerTraverser

        ztapi.provideView(ISimpleReadContainer, IRequest, IPublishTraverse,
                          '', ContainerTraverser)

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

        self.publication.beforeTraversal(self.request)
        self.assertEqual(list(queryInteraction().participations),
                         [self.request])
        self.assertEqual(self.request.principal.id, 'anonymous')
        root = self.publication.getApplication(self.request)
        self.publication.callTraversalHooks(self.request, root)
        self.assertEqual(self.request.principal.id, 'anonymous')
        ob = self.publication.traverseName(self.request, root, 'f1')
        self.publication.callTraversalHooks(self.request, ob)
        self.assertEqual(self.request.principal.id, 'test.anonymous')
        ob = self.publication.traverseName(self.request, ob, 'f2')
        self.publication.afterTraversal(self.request, ob)
        self.assertEqual(self.request.principal.id, 'test.bob')
        self.assertEqual(list(queryInteraction().participations),
                         [self.request])
        self.publication.endRequest(self.request, ob)
        self.assertEqual(queryInteraction(), None)
Exemplo n.º 19
0
    def testViewOnException(self):
        from zope.interface import Interface
        class E1(Exception):
            pass

        ztapi.setDefaultViewName(E1, 'name',
                                 layer=None,
                                 type=self.presentation_type)
        view_text = 'You had a conflict error'
        ztapi.provideView(E1, self.presentation_type, Interface,
                          'name', lambda obj, request: lambda: view_text)
        try:
            raise E1
        except:
            pass
        self.publication.handleException(
            self.object, self.request, sys.exc_info(), retry_allowed=False)
        self.assertEqual(self.request.response._result, view_text)
Exemplo n.º 20
0
    def testViewMapper(self):
        the_view = "This is the view"
        the_view_name = "some view name"
        def ViewMaker(*args, **kw):
            return the_view

        from zope.component.interfaces import IPresentationRequest

        ztapi.provideView(I1, IPresentationRequest, Interface,
                          the_view_name, ViewMaker)

        class MyRequest(object):
            implements(IPresentationRequest)

        request = MyRequest()

        namespace = self.t.pt_getContext(InstanceWithContext(self.context),
                                         request)
        views = namespace['views']
        self.failUnless(the_view is views[the_view_name])
Exemplo n.º 21
0
 def testNoViewOnClassicClassException(self):
     from zope.interface import Interface
     from types import ClassType
     class ClassicError:
         __metaclass__ = ClassType
     class IClassicError(Interface):
         pass
     classImplements(ClassicError, IClassicError)
     ztapi.setDefaultViewName(IClassicError, 'name', self.presentation_type)
     view_text = 'You made a classic error ;-)'
     ztapi.provideView(IClassicError, self.presentation_type, Interface,
                       'name', lambda obj,request: lambda: view_text)
     try:
         raise ClassicError
     except:
         pass
     self.publication.handleException(
         self.object, self.request, sys.exc_info(), retry_allowed=False)
     # check we don't get the view we registered
     self.failIf(''.join(self.request.response._result) == view_text)
     # check we do actually get something
     self.failIf(''.join(self.request.response._result) == '')
Exemplo n.º 22
0
    def testDenyDirectMethodAccess(self):
        pub = self.klass(self.db)
        class I(Interface):
            pass

        class C(object):
            implements(I)

            def foo(self):
                return 'bar'

        class V(object):
            def __init__(self, context, request):
                pass
            implements(IXMLRPCPresentation)

        ob = C()
        r = self._createRequest('/foo', pub)

        ztapi.provideView(I, IXMLRPCPresentation, Interface, 'view', V)
        ztapi.setDefaultViewName(I, 'view', type=IXMLRPCPresentation)
        self.assertRaises(NotFound, pub.traverseName, r, ob, 'foo')
Exemplo n.º 23
0
def tearDown(test):
    # clean up the views we registered:
    
    # we use the fact that registering None unregisters whatever is
    # registered. We can't use an unregistration call because that
    # requires the object that was registered and we don't have that handy.
    # (OK, we could get it if we want. Maybe later.)

    ztapi.provideView(zope.app.folder.folder.IFolder,
                        zope.publisher.interfaces.xmlrpc.IXMLRPCRequest,
                        zope.interface,
                        'contents',
                        None,
                        )
    ztapi.provideView(zope.app.folder.folder.IFolder,
                        zope.publisher.interfaces.xmlrpc.IXMLRPCRequest,
                        zope.interface,
                        'contents',
                        None,
                        )
    
    setup.tearDownTestAsModule(test)
Exemplo n.º 24
0
    def testViewOnException(self):
        from zope.interface import Interface

        class E1(Exception):
            pass

        ztapi.setDefaultViewName(E1,
                                 'name',
                                 layer=None,
                                 type=self.presentation_type)
        view_text = 'You had a conflict error'
        ztapi.provideView(E1, self.presentation_type, Interface, 'name',
                          lambda obj, request: lambda: view_text)
        try:
            raise E1
        except:
            pass
        self.publication.handleException(self.object,
                                         self.request,
                                         sys.exc_info(),
                                         retry_allowed=False)
        self.assertEqual(self.request.response._result, view_text)
Exemplo n.º 25
0
def setUpTraversal():
    from zope.app.traversing.browser import SiteAbsoluteURL, AbsoluteURL

    ztapi.provideAdapter(None, ITraverser, Traverser)
    ztapi.provideAdapter(None, ITraversable, DefaultTraversable)

    ztapi.provideAdapter(
        ISimpleReadContainer, ITraversable, ContainerTraversable)
    ztapi.provideAdapter(
        None, IPhysicallyLocatable, LocationPhysicallyLocatable)
    ztapi.provideAdapter(
        IContainmentRoot, IPhysicallyLocatable, RootPhysicallyLocatable)

    # set up etc namespace
    ztapi.provideAdapter(None, ITraversable, etc, name="etc")
    ztapi.provideView(None, None, ITraversable, "etc", etc)

    ztapi.browserView(None, "absolute_url", AbsoluteURL)
    ztapi.browserView(IContainmentRoot, "absolute_url", SiteAbsoluteURL)

    ztapi.browserView(None, '', AbsoluteURL, providing=IAbsoluteURL)
    ztapi.browserView(IContainmentRoot, '', SiteAbsoluteURL,
                      providing=IAbsoluteURL)
def tearDown(test):
    # clean up the views we registered:

    # we use the fact that registering None unregisters whatever is
    # registered. We can't use an unregistration call because that
    # requires the object that was registered and we don't have that handy.
    # (OK, we could get it if we want. Maybe later.)

    ztapi.provideView(IFolder,
                        ISOAPRequest,
                        zope.interface,
                        'contents',
                        None,
                        )
    ztapi.provideView(IFolder,
                        ISOAPRequest,
                        zope.interface,
                        'contents',
                        None,
                        )

    globs.clear()
    del sys.modules[name]
    def testDenyDirectMethodAccess(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

            def foo(self):
                return "bar"

        class V(object):
            def __init__(self, context, request):
                pass

            implements(ISOAPPresentation)

        ob = C()
        r = self._createRequest("/foo", pub)

        ztapi.provideView(I, ISOAPPresentation, Interface, "view", V)
        ztapi.setDefaultViewName(I, "view", type=ISOAPPresentation)
        self.assertRaises(NotFound, pub.traverseName, r, ob, "foo")
Exemplo n.º 28
0
    def testDenyDirectMethodAccess(self):
        pub = self.klass(self.db)

        class I(Interface):
            pass

        class C(object):
            implements(I)

            def foo(self):
                return 'bar'

        class V(object):
            def __init__(self, context, request):
                pass

            implements(IXMLRPCPresentation)

        ob = C()
        r = self._createRequest('/foo', pub)

        ztapi.provideView(I, IXMLRPCPresentation, Interface, 'view', V)
        ztapi.setDefaultViewName(I, 'view', type=IXMLRPCPresentation)
        self.assertRaises(NotFound, pub.traverseName, r, ob, 'foo')
Exemplo n.º 29
0
    def testHandlingSystemErrors(self):

        # Generally, when there is a view for an excepton, we assume
        # it is a user error, not a system error and we don't log it.

        from zope.testing import loggingsupport
        handler = loggingsupport.InstalledHandler('SiteError')

        self.testViewOnException()

        self.assertEqual(
            str(handler),
            'SiteError ERROR\n'
            '  Error while reporting an error to the Error Reporting utility')

        # Here we got a single log record, because we havdn't
        # installed an error reporting utility.  That's OK.

        handler.uninstall()
        handler = loggingsupport.InstalledHandler('SiteError')

        # Now, we'll register an exception view that indicates that we
        # have a system error.

        from zope.interface import Interface, implements
        class E2(Exception):
            pass

        ztapi.setDefaultViewName(E2, 'name',
                                 layer=self.presentation_type,
                                 type=self.presentation_type)
        view_text = 'You had a conflict error'

        from zope.app.exception.interfaces import ISystemErrorView
        class MyView:
            implements(ISystemErrorView)
            def __init__(self, context, request):
                pass

            def isSystemError(self):
                return True

            def __call__(self):
                return view_text

        ztapi.provideView(E2, self.presentation_type, Interface,
                          'name', MyView)
        try:
            raise E2
        except:
            self.publication.handleException(
                self.object, self.request, sys.exc_info(), retry_allowed=False)

        # Now, since the view was a system error view, we should have
        # a log entry for the E2 error (as well as the missing
        # error reporting utility).
        self.assertEqual(
            str(handler),
            'SiteError ERROR\n'
            '  Error while reporting an error to the Error Reporting utility\n'
            'SiteError ERROR\n'
            '  http://test.url'
            )

        handler.uninstall()
Exemplo n.º 30
0
    def testHandlingSystemErrors(self):

        # Generally, when there is a view for an excepton, we assume
        # it is a user error, not a system error and we don't log it.

        from zope.testing import loggingsupport
        handler = loggingsupport.InstalledHandler('SiteError')

        self.testViewOnException()

        self.assertEqual(
            str(handler), 'SiteError ERROR\n'
            '  Error while reporting an error to the Error Reporting utility')

        # Here we got a single log record, because we haven't
        # installed an error reporting utility.  That's OK.

        handler.uninstall()
        handler = loggingsupport.InstalledHandler('SiteError')

        # Now, we'll register an exception view that indicates that we
        # have a system error.

        from zope.interface import Interface, implements

        class E2(Exception):
            pass

        ztapi.setDefaultViewName(E2,
                                 'name',
                                 layer=self.presentation_type,
                                 type=self.presentation_type)
        view_text = 'You had a conflict error'

        from zope.app.exception.interfaces import ISystemErrorView

        class MyView:
            implements(ISystemErrorView)

            def __init__(self, context, request):
                pass

            def isSystemError(self):
                return True

            def __call__(self):
                return view_text

        ztapi.provideView(E2, self.presentation_type, Interface, 'name',
                          MyView)
        try:
            raise E2
        except:
            self.publication.handleException(self.object,
                                             self.request,
                                             sys.exc_info(),
                                             retry_allowed=False)

        # Now, since the view was a system error view, we should have
        # a log entry for the E2 error (as well as the missing
        # error reporting utility).
        self.assertEqual(
            str(handler), 'SiteError ERROR\n'
            '  Error while reporting an error to the Error Reporting utility\n'
            'SiteError ERROR\n'
            '  http://test.url')

        handler.uninstall()
Exemplo n.º 31
0
def setUp(test=None):
    """Set up the test fixture for schooltool.app.browser doctests.

    Performs what is called a "placeless setup" in the Zope 3 world, then sets
    up annotations, relationships, and registers widgets as views for some
    schema fields.

    In effect, duplicates a subset of ZCML configuration -- just enough to
    actually render our page templates in unit tests.
    """
    setup.placefulSetUp()
    setup.setUpAnnotations()
    setup.setUpTraversal()
    # relationships
    setUpRelationships()
    # widgets
    ztapi.browserViewProviding(IPassword, PasswordWidget, IInputWidget)
    ztapi.browserViewProviding(ITextLine, TextWidget, IInputWidget)
    ztapi.browserViewProviding(IText, TextAreaWidget, IInputWidget)
    ztapi.browserViewProviding(IBytes, BytesWidget, IInputWidget)
    ztapi.browserViewProviding(IBool, CheckBoxWidget, IInputWidget)
    ztapi.browserViewProviding(IDate, DateWidget, IInputWidget)
    ztapi.browserViewProviding(IInt, IntWidget, IInputWidget)
    ztapi.browserViewProviding(IChoice, ChoiceInputWidget, IInputWidget)
    ztapi.browserViewProviding(ICollection, CollectionInputWidget, IInputWidget)

    ztapi.provideMultiView((IChoice, IIterableVocabulary), IBrowserRequest,
                           IInputWidget, '', DropdownWidget)

    ztapi.provideMultiView((ISet, IChoice), IBrowserRequest,
                           IInputWidget, '', ChoiceCollectionInputWidget)
    ztapi.provideMultiView((IList, IChoice), IBrowserRequest,
                           IInputWidget, '', ChoiceCollectionInputWidget)
    ztapi.provideMultiView((IList, IVocabularyTokenized), IBrowserRequest,
                           IInputWidget, '', OrderedMultiSelectWidget)
    # XXX MultiSelectWidget doesn't work with sets :/
    #     http://www.zope.org/Collectors/Zope3-dev/360
    ztapi.provideMultiView((ISet, IIterableVocabulary), IBrowserRequest,
                           IInputWidget, '', MultiSelectWidget)

    # errors in forms
    ztapi.browserViewProviding(IWidgetInputError, WidgetInputErrorView,
                               IWidgetInputErrorView)


    # Now, the question is: does the speed of the tests run with the
    # setup below justify this complex setup that duplicates the ZCML?
    # For now, I say yes. -- not mg, perhaps alga or gintas

    # ++view++
    ztapi.provideView(None, None, ITraversable, 'view', view)
    ztapi.provideView(None, None, ITraversable, 'resource', resource)

    # schooltool: namespace in tal
    provideAdapter(SchoolToolAPI, (None,), IPathAdapter, 'schooltool')

    # sortby: namespace in tal
    provideAdapter(SortBy, (None,), IPathAdapter, 'sortby')

    # standard_macros, schooltool_macros and schooltool_navigation
    ztapi.browserView(None, 'standard_macros', StandardMacros)
    ztapi.browserView(None, 'view_macros',
                      SimpleViewClass("../../skin/templates/view_macros.pt"))

    ztapi.browserView(None, 'schooltool_macros', SchoolToolMacros)
    ztapi.browserView(None, 'calendar_macros',
                      SimpleViewClass("./templates/calendar_macros.pt"))
    ztapi.browserView(None, 'generic_macros',
                      SimpleViewClass("../../skin/templates/generic_macros.pt"))

    # form macros
    ztapi.browserView(None, 'form_macros', FormMacros)
    import zope.formlib
    base = zope.formlib.__path__[0]
    ztapi.browserView(None, 'widget_macros',
                      SimpleViewClass(os.path.join(base, 'widget_macros.pt')))

    # resources
    class ResourceStub:
        def __init__(self, request):
            self.request = request
        def __getitem__(self, key):
            return ResourceStub(self.request)
        def __call__(self):
            return "a dummy resource"

    for name in ['layout.css', 'schooltool.css', 'schooltool.js',
                 'next.png', 'prev.png', 'favicon.ico',
                 'print.css', 'jquery.js',
                 'zonki-regular.png']:
        ztapi.browserResource(name, ResourceStub)

    # menus
    ztapi.browserView(None, 'view_get_menu', MenuAccessView)
    provideUtility(BrowserMenuStub('schooltool_actions'), IBrowserMenu,
                   'schooltool_actions')

    # `provider` TALES namespaces
    from zope.browserpage import metaconfigure
    from zope.contentprovider import tales
    metaconfigure.registerType('provider', tales.TALESProviderExpression)

    # viewlet manager registrations
    from zope.viewlet import manager
    from schooltool import skin
    name = 'schooltool.Header'
    provideAdapter(
        manager.ViewletManager(name, skin.IHeaderManager),
        (Interface, IDefaultBrowserLayer, IBrowserView),
        skin.IHeaderManager,
        name=name)

    name = 'schooltool.JavaScript'
    provideAdapter(
        manager.ViewletManager(name, skin.IJavaScriptManager),
        (Interface, IDefaultBrowserLayer, IBrowserView),
        skin.IJavaScriptManager,
        name=name)

    name = 'schooltool.CSS'
    provideAdapter(
        manager.ViewletManager(name, skin.ICSSManager),
        (Interface, IDefaultBrowserLayer, IBrowserView),
        skin.ICSSManager,
        name=name)

    name = 'schooltool.MenuBar'
    provideAdapter(
        manager.ViewletManager(name, skin.skin.IMenuBarMenuManager),
        (Interface, IDefaultBrowserLayer, IBrowserView),
        skin.skin.IMenuBarMenuManager,
        name=name)

    name = 'schooltool.NavigationMenu'
    provideAdapter(
        manager.ViewletManager(name, skin.skin.INavigationManager),
        (Interface, IDefaultBrowserLayer, IBrowserView),
        skin.skin.INavigationManager,
        name=name)

    name = 'schooltool.ActionsMenu'
    provideAdapter(
        manager.ViewletManager(name, skin.skin.IActionMenuManager),
        (Interface, IDefaultBrowserLayer, IBrowserView),
        skin.skin.IActionMenuManager,
        name=name)