Ejemplo n.º 1
0
    def testSkinnedPageView(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)

        xmlconfig(StringIO(template %
            '''
            <browser:layer name="layer" />
            <browser:skin name="skinny" layers="layer" />
            <browser:pages
                for="*"
                class="zope.app.component.tests.views.V1"
                permission="zope.Public"
                >
             
              <browser:page name="index.html" attribute="index" />
            </browser:pages>
            <browser:pages
                for="*"
                class="zope.app.component.tests.views.V1"
                layer="layer"
                permission="zope.Public"
                >
            
              <browser:page name="index.html" attribute="action" />
            </browser:pages>
            '''
            ))

        v = zapi.getMultiAdapter((ob, request), name='index.html')
        self.assertEqual(v(), 'V1 here')
        skinny = zapi.getUtility(ISkin, 'skinny')
        v = zapi.getMultiAdapter((ob, TestRequest(skin=skinny)),
                                 name='index.html')
        self.assertEqual(v(), 'done')
Ejemplo n.º 2
0
    def testPageViews(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)
        test3 = os.path.join(tests_path, 'testfiles', 'test3.pt')

        xmlconfig(StringIO(template %
            '''
            <browser:pages
                class="zope.app.component.tests.views.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                >

              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
              <browser:page name="test.html" template="%s" />
            </browser:pages>
            ''' % test3
            ))

        v = zapi.getMultiAdapter((ob, request), name='index.html')
        self.assertEqual(v(), 'V1 here')
        v = zapi.getMultiAdapter((ob, request), name='action.html')
        self.assertEqual(v(), 'done')
        v = zapi.getMultiAdapter((ob, request), name='test.html')
        self.assertEqual(str(v()), '<html><body><p>done</p></body></html>\n')
Ejemplo n.º 3
0
    def testProtectedPageViews(self):
        ztapi.provideUtility(IPermission, Permission('p', 'P'), 'p')

        request = TestRequest()
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)

        xmlconfig(StringIO(template %
            '''
            <include package="zope.app.security" file="meta.zcml" />
            
            <permission id="zope.TestPermission" title="Test permission" />

            <browser:pages
                class="zope.app.component.tests.views.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.TestPermission"
                >
             
              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
            </browser:pages>
            '''
            ))

        v = zapi.getMultiAdapter((ob, request), name='index.html')
        v = ProxyFactory(v)
        zope.security.management.getInteraction().add(request)
        self.assertRaises(Exception, v)
        v = zapi.getMultiAdapter((ob, request), name='action.html')
        v = ProxyFactory(v)
        self.assertRaises(Exception, v)
Ejemplo n.º 4
0
    def test_create(self):

        class Adding(object):

            implements(IAdding)

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

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(
                    ob.__dict__,
                    {'args': ("bar", "baz"),
                     'kw': {'email': '*****@*****.**'},
                     '_foo': 'foo',
                    })
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = zapi.getMultiAdapter((adding, request), name='addthis')
        content = view.create('a',0,abc='def')

        self.failUnless(isinstance(content, C))
        self.assertEqual(content.args, ('a', 0))
        self.assertEqual(content.kw, {'abc':'def'})
Ejemplo n.º 5
0
    def test_createAndAdd_w_adapter(self):

        class Adding(object):

            implements(IAdding)

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

            def add(self, ob):
                self.ob = ob
                self.test.assertEqual(ob.__dict__, {'foo': 'bar'})
                return ob
            def nextURL(self):
                return "."

        adding = Adding(self)
        self._invoke_add(
            schema=IBar, name="addthis", permission="zope.Public",
            label="Add this", content_factory=Foo, class_=FooV,
            arguments=None, keyword_arguments=None,
            set_before_add=["bar"], set_after_add=None,
            fields=None
            )
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = zapi.getMultiAdapter((adding, request), name='addthis')

        view.createAndAdd({'bar': 'bar'})
Ejemplo n.º 6
0
    def testResource(self):
        self.assertEqual(
            zapi.queryMultiAdapter((ob, request), name='zmi_icon'), None)

        import zope.app.publisher.browser.tests as p
        path = os.path.dirname(p.__file__)
        path = os.path.join(path, 'testfiles', 'test.gif')

        xmlconfig(StringIO(template % (
            '''
            <browser:resource name="zmi_icon_res"
                      image="%s" />
            <browser:icon name="zmi_icon"
                      for="zope.app.component.tests.views.IC"
                      resource="zmi_icon_res" />
            ''' % path
            )))

        view = zapi.getMultiAdapter((ob, request), name='zmi_icon')
        rname = "zmi_icon_res"
        self.assertEqual(
            view(),
            '<img src="http://127.0.0.1/@@/%s" alt="IC" width="16" '
            'height="16" border="0" />'
            % rname)

        resource = ProxyFactory(zapi.getAdapter(request, name=rname))

        self.assertRaises(Forbidden, getattr, resource, '_testData')
        resource = removeSecurityProxy(resource)
        self.assertEqual(resource._testData(), open(path, 'rb').read())
Ejemplo n.º 7
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError("You must select the type of object to add.")

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name  = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if zapi.queryView(self, view_name, self.request) is not None:
            url = "%s/%s=%s" % (
                zapi.getMultiAdapter((self, self.request), name=u"absolute_url"),
                type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        factory = zapi.getUtility(IFactory, type_name)
        content = factory()

        notify(ObjectCreatedEvent(content))
        self.add(content)
        self.request.response.redirect(self.nextURL())
Ejemplo n.º 8
0
 def nextURL(self):
     """See zope.app.container.interfaces.IAdding"""
     # XXX this is definitely not right for all or even most uses
     # of Five, but can be overridden by an AddView subclass, using
     # the class attribute of a zcml:addform directive
     return str(zapi.getMultiAdapter((self.context, self.request),
                                     name=u"absolute_url")) + '/manage_main'
Ejemplo n.º 9
0
    def testTraversalOfPageForViewWithPublishTraverse(self):
        """Tests proper traversal of a page defined for a view.
        
        This test is different from testTraversalOfPageForView in that it
        tests the behavior on a view that has a publishTraverse method --
        the implementation of the lookup is slightly different in such a
        case.
        """
        xmlconfig(StringIO(template %
            '''
            <browser:view
                name="test"
                class="zope.app.publisher.browser.tests.test_directives.VT"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public" />

            <browser:page name="index.html"
                for="zope.app.component.tests.views.IV" 
                class="zope.app.publisher.browser.tests.test_directives.CV"
                permission="zope.Public" />
            '''
            ))

        view = zapi.getMultiAdapter((ob, request), name='test')
        view = removeSecurityProxy(view)
        view.publishTraverse(request, 'index.html')
Ejemplo n.º 10
0
    def testNamedViewPageViewsNoDefault(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)
        test3 = os.path.join(tests_path, 'testfiles', 'test3.pt')

        xmlconfig(StringIO(template %
            '''
            <browser:view
                name="test"
                class="zope.app.component.tests.views.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                >

              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
              <browser:page name="test.html" template="%s" />
            </browser:view>
            ''' % test3
            ))

        view = zapi.getMultiAdapter((ob, request), name='test')
        view = removeSecurityProxy(view)
        self.assertEqual(view.browserDefault(request)[1], (u'index.html', ))


        v = view.publishTraverse(request, 'index.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'V1 here')
        v = view.publishTraverse(request, 'action.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'done')
        v = view.publishTraverse(request, 'test.html')
        v = removeSecurityProxy(v)
        self.assertEqual(str(v()), '<html><body><p>done</p></body></html>\n')
Ejemplo n.º 11
0
    def testBasicContext_unicode(self):
        #Tests so that AbsoluteURL handle unicode names as well
        request = TestRequest()
        root = Root()
        root.__name__ = u'\u0439'

        content = contained(TrivialContent(), root, name=u'\u0442')
        content = contained(TrivialContent(), content, name=u'\u0435')
        content = contained(TrivialContent(), content, name=u'\u0441')
        view = zapi.getMultiAdapter((content, request), name='absolute_url')
        self.assertEqual(str(view),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')
        self.assertEqual(view(),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')
        self.assertEqual(unicode(view),
                         u'http://127.0.0.1/\u0439/\u0442/\u0435/\u0441')
        self.assertEqual(absoluteURL(content, request),
                         'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81')

        breadcrumbs = view.breadcrumbs()
        self.assertEqual(breadcrumbs,
                         ({'name':  '', 'url': 'http://127.0.0.1'},
                          {'name': u'\u0439', 'url': 'http://127.0.0.1/%D0%B9'},
                          {'name': u'\u0442',
                           'url': 'http://127.0.0.1/%D0%B9/%D1%82'},
                          {'name': u'\u0435',
                           'url': 'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5'},
                          {'name': u'\u0441',
                           'url':
                           'http://127.0.0.1/%D0%B9/%D1%82/%D0%B5/%D1%81'},
                          ))
Ejemplo n.º 12
0
    def action(self, type_name='', id=''):
        if not type_name:
            raise UserError("You must select the type of object to add.")

        if type_name.startswith('@@'):
            type_name = type_name[2:]

        if '/' in type_name:
            view_name = type_name.split('/', 1)[0]
        else:
            view_name = type_name

        if zapi.queryView(self, view_name, self.request) is not None:
            url = "%s/%s=%s" % (zapi.getMultiAdapter(
                (self, self.request), name=u"absolute_url"), type_name, id)
            self.request.response.redirect(url)
            return

        if not self.contentName:
            self.contentName = id

        factory = zapi.getUtility(IFactory, type_name)
        content = factory()

        notify(ObjectCreatedEvent(content))
        self.add(content)
        self.request.response.redirect(self.nextURL())
Ejemplo n.º 13
0
    def testProtectedNamedViewPageViews(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)

        xmlconfig(StringIO(template %
            '''
            <include package="zope.app.security" file="meta.zcml" />

            <permission id="zope.TestPermission" title="Test permission" />

            <browser:view
                name="test"
                class="zope.app.component.tests.views.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                >
             
              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
            </browser:view>
            '''
            ))

        view = zapi.getMultiAdapter((ob, request), name='test')
        self.assertEqual(view.browserDefault(request)[1], (u'index.html', ))

        v = view.publishTraverse(request, 'index.html')
        self.assertEqual(v(), 'V1 here')
Ejemplo n.º 14
0
    def testAddForm(self):
        self.assertEqual(
            zapi.queryMultiAdapter((ob, request), name='add.html'),
            None)
        xmlconfig(StringIO(template % ("""
          <view
              type="zope.publisher.interfaces.browser.IBrowserRequest"
              for="zope.schema.interfaces.ITextLine"
              provides="zope.app.form.interfaces.IInputWidget"
              factory="zope.app.form.browser.TextWidget"
              permission="zope.Public"
              />

          <browser:addform
              for="zope.app.form.browser.tests.test_directives.IC"
              schema="zope.app.form.browser.tests.test_directives.Schema"
              name="add.html"
              label="Add a ZPT page"
              fields="text"
              permission="zope.Public" />
            """)))

        v = zapi.getMultiAdapter((ob, request), name='add.html')
        # expect to fail as standard macros are not configured
        self.assertRaises(TraversalError, v)
Ejemplo n.º 15
0
    def __call__(self):
        """Render the current value
        """

        if self._renderedValueSet():
            value = self._data
        else:
            value = self.context.default
            
        if value == self.context.missing_value:
            value = self._translate(_("SourceDisplayWidget-missing",
                                      default="Nothing"))
        else:
            terms = zapi.getMultiAdapter(
                (self.source, self.request),
                zope.app.form.browser.interfaces.ITerms,
                )
                
            try:
                term = terms.getTerm(value)
            except LookupError:
                value = self._translate(_("SourceDisplayWidget-invalid",
                                          default="Invalid value"))
            else:
                value = self.renderTermForDisplay(term)

        return value
Ejemplo n.º 16
0
 def __init__(self, field, source, request):
     super(SourceInputWidget, self).__init__(field, request)
     self.source = source
     self.terms = zapi.getMultiAdapter(
         (source, self.request),
         zope.app.form.browser.interfaces.ITerms,
         )
Ejemplo n.º 17
0
 def topicContent(self):
     """ render the source of the help topic """
     source = zapi.createObject(self.context.type,
                                self.context.source)
     view = zapi.getMultiAdapter((source, self.request))
     html = view.render()
     return html
Ejemplo n.º 18
0
    def testNamedViewPageViewsCustomTraversr(self):
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)

        xmlconfig(StringIO(template %
            '''
            <browser:view
                name="test"
                class="zope.app.publisher.browser.tests.test_directives.V1"
                for="zope.app.component.tests.views.IC"
                permission="zope.Public"
                >

              <browser:page name="index.html" attribute="index" />
              <browser:page name="action.html" attribute="action" />
            </browser:view>
            '''
            ))

        view = zapi.getMultiAdapter((ob, request), name='test')
        view = removeSecurityProxy(view)
        self.assertEqual(view.browserDefault(request)[1], (u'index.html', ))


        v = view.publishTraverse(request, 'index.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'V1 here')
        v = view.publishTraverse(request, 'action.html')
        v = removeSecurityProxy(v)
        self.assertEqual(v(), 'done')
Ejemplo n.º 19
0
 def test_cookie_tree_pre_expanded(self):
     request = self.makeRequestWithVar()
     view = zapi.getMultiAdapter((self.root_obj, request),
                                 name='cookie_tree')
     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)
Ejemplo n.º 20
0
    def __call__(self):
        name = self.__name__
        if name.startswith('++resource++'):
            name = name[12:]

        site = getSite()
        url = str(zapi.getMultiAdapter((site, self.request), IAbsoluteURL))
        return "%s/@@/%s" % (url, name)
Ejemplo n.º 21
0
    def nextURL(self):
        v = zapi.queryMultiAdapter(
            (self.added_object, self.request), name="registration.html")
        if v is not None:
            url = str(zapi.getMultiAdapter(
                (self.added_object, self.request), name='absolute_url'))
            return url + "/@@registration.html"

        return super(ComponentAdding, self).nextURL()
Ejemplo n.º 22
0
    def test_hooks(self):

        class Adding(object):
            implements(IAdding)

        adding = Adding()
        self._invoke_add()
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()

        request.form.update(dict([
            ("field.%s" % k, v)
            for (k, v) in dict(SampleData.__dict__).items()
            ]))
        request.form[Update] = ''
        view = zapi.getMultiAdapter((adding, request), name='addthis')

        # Add hooks to V

        l=[None]

        def add(aself, ob):
            l[0] = ob
            self.assertEqual(
                ob.__dict__,
                {'args': ("bar", "baz"),
                 'kw': {'email': '*****@*****.**'},
                 '_foo': 'foo',
                 })
            return ob

        V.add = add

        V.nextURL = lambda self: 'next'

        try:
            self.assertEqual(view.update(), '')

            self.assertEqual(view.errors, ())

            self.assertEqual(l[0].extra1, "extra1")
            self.assertEqual(l[0].extra2, "extra2")
            self.assertEqual(l[0].name, "foo")
            self.assertEqual(l[0].address, "aa")

            self.assertEqual(request.response.getHeader("Location"), "next")

            # Verify that calling update again doesn't do anything.
            l[0] = None
            self.assertEqual(view.update(), '')
            self.assertEqual(l[0], None)

        finally:
            # Uninstall hooks
            del V.add
            del V.nextURL
Ejemplo n.º 23
0
 def _getWidget(self, i):
     field = self.context.value_type
     if self.subwidget is not None:
         widget = self.subwidget(field, self.request)
     else:
         widget = zapi.getMultiAdapter(
             (field, self.request), IDisplayWidget)
     widget.setPrefix('%s.%d.' % (self.name, i))
     return widget
Ejemplo n.º 24
0
    def test_body_set(self):
        context = DummySetupEnviron()
        adapted = zapi.getMultiAdapter((self._obj, context), IBody)
        adapted.body = self._BODY
        self._verifyImport(self._obj)
        self.assertEqual(adapted.body, self._BODY)

        # now in update mode
        context._should_purge = False
        adapted = zapi.getMultiAdapter((self._obj, context), IBody)
        adapted.body = self._BODY
        self._verifyImport(self._obj)
        self.assertEqual(adapted.body, self._BODY)

        # and again in update mode
        adapted = zapi.getMultiAdapter((self._obj, context), IBody)
        adapted.body = self._BODY
        self._verifyImport(self._obj)
        self.assertEqual(adapted.body, self._BODY)
Ejemplo n.º 25
0
    def test_node_set(self):
        context = DummySetupEnviron()
        adapted = zapi.getMultiAdapter((self._obj, context), INode)
        adapted.node = parseString(self._XML).documentElement
        self._verifyImport(self._obj)
        self.assertEqual(adapted.node.toprettyxml(' '), self._XML)

        # now in update mode
        context._should_purge = False
        adapted = zapi.getMultiAdapter((self._obj, context), INode)
        adapted.node = parseString(self._XML).documentElement
        self._verifyImport(self._obj)
        self.assertEqual(adapted.node.toprettyxml(' '), self._XML)

        # and again in update mode
        adapted = zapi.getMultiAdapter((self._obj, context), INode)
        adapted.node = parseString(self._XML).documentElement
        self._verifyImport(self._obj)
        self.assertEqual(adapted.node.toprettyxml(' '), self._XML)
Ejemplo n.º 26
0
 def error(self):
     if self._error:
         errormessages = []
         keys = self._error.keys(); keys.sort()
         for key in keys:
             errormessages.append(str(key) + ': ')
             errormessages.append( zapi.getMultiAdapter((self._error[key], self.request),
                                     IWidgetInputErrorView).snippet())
             errormessages.append(str(key) + ', ')
         return ''.join(errormessages[0:-1])
     return ""
Ejemplo n.º 27
0
    def __call__(self):
        name = self.__name__
        container = self.__parent__

        # TODO Zope 3 uses site = getSite() instead of container here
        # and the @@ resource access view
        url = str(zapi.getMultiAdapter((container, self.request), IAbsoluteURL))
        url = urllib.unquote(url)
        if not isinstance(container, DirectoryResource):
            name = '++resource++%s' % name
        return "%s/%s" % (url, name)
Ejemplo n.º 28
0
    def __call__(self):
        name = self.__name__
        container = self.__parent__

        # TODO Zope 3 uses site = getSite() instead of container here
        # and the @@ resource access view
        url = str(zapi.getMultiAdapter((container, self.request), IAbsoluteURL))
        url = urllib.unquote(url)
        if not isinstance(container, DirectoryResource):
            name = '++resource++%s' % name
        return "%s/%s" % (url, name)
Ejemplo n.º 29
0
    def testSourceView(self):
        page = ZPTPage()

        utext = u'another test\n' # The source will grow a newline if ommited
        html = u"<html><body>%s</body></html>\n" % (utext, )
        page.setSource(html, content_type='text/plain')
        request = TestRequest()

        view = zapi.getMultiAdapter((page, request), name='source.html')

        self.assertEqual(str(view), html)
        self.assertEqual(view(), html)
Ejemplo n.º 30
0
    def testProtectedtemplate(self):

        path = os.path.join(tests_path, 'testfiles', 'test.pt')

        request = TestRequest()
        self.assertEqual(zapi.queryMultiAdapter((ob, request), name='test'),
                         None)

        xmlconfig(StringIO(template %
            '''
            <include package="zope.app.security" file="meta.zcml" />

            <permission id="zope.TestPermission" title="Test permission" />

            <browser:page
                name="xxx.html"
                template="%s"
                permission="zope.TestPermission"
                for="zope.app.component.tests.views.IC" />
            ''' % path
            ))

        xmlconfig(StringIO(template %
            '''
            <browser:page
                name="index.html"
                template="%s"
                permission="zope.Public"
                for="zope.app.component.tests.views.IC" />
            ''' % path
            ))

        v = zapi.getMultiAdapter((ob, request), name='xxx.html')
        v = ProxyFactory(v)
        zope.security.management.getInteraction().add(request)
        self.assertRaises(Exception, v)

        v = zapi.getMultiAdapter((ob, request), name='index.html')
        v = ProxyFactory(v)
        self.assertEqual(v().strip(), '<html><body><p>test</p></body></html>')
Ejemplo n.º 31
0
 def __getitem__(self, key):
     key = self.aliases.get(key, key)
     context = self.context
     request = self.request
     for name in self.macro_pages:
         page = zapi.getMultiAdapter((context, request), name=name)
         try:
             v = page[key]
         except KeyError:
             pass
         else:
             return v
     raise KeyError(key)
Ejemplo n.º 32
0
 def __getitem__(self, key):
     key = self.aliases.get(key, key)
     context = self.context
     request = self.request
     for name in self.macro_pages:
         page = zapi.getMultiAdapter((context, request), name=name)
         try:
             v = page[key]
         except KeyError:
             pass
         else:
             return v
     raise KeyError, key
Ejemplo n.º 33
0
    def testAttributeProtectedView(self):
        xmlconfig(StringIO(template %
            '''
            <view name="test"
                  factory="zope.app.component.tests.views.V1"
                  for="zope.app.component.tests.views.IC"
                  type="zope.app.component.tests.views.IV"
                  permission="zope.Public"
                  allowed_attributes="action"
                  />
            '''
            ))

        v = ProxyFactory(zapi.getMultiAdapter((Ob(), Request(IV)), name='test'))
        self.assertEqual(v.action(), 'done')
        self.assertRaises(Exception, getattr, v, 'index')
Ejemplo n.º 34
0
    def getIntroduction(self):
        text = self.context.__description__ or self.schema.__doc__
        text = translate(text, context=self.request, default=text)

        # Determine common whitespace ...
        cols = len(re.match('^[ ]*', text).group())
        # ... and clean it up.
        text = re.sub('\n[ ]{%i}' %cols, '\n', text).strip()

        if not text:
            return u''

        # Render the description as ReST.
        source = zapi.createObject('zope.source.rest', text)
        renderer = zapi.getMultiAdapter((source, self.request))
        return renderer.render()
Ejemplo n.º 35
0
    def breadcrumbs(self):
        context = aq_inner(self.context)
        container = aq_parent(context)
        request = self.request

        name = context.getId()

        if container is None or self._isVirtualHostRoot() \
            or not ITraversable.providedBy(container):
            return ({'name': name, 'url': context.absolute_url()}, )

        view = zapi.getMultiAdapter((container, request), IAbsoluteURL)
        base = tuple(view.breadcrumbs())
        base += ({'name': name, 'url': ("%s/%s" % (base[-1]['url'], name))}, )

        return base
Ejemplo n.º 36
0
    def test_class_w_implements(self):
        xmlconfig(StringIO(template %
            '''
            <browser:page
                name="test"
                class="
             zope.app.publisher.browser.tests.test_directives.C_w_implements"
                for="zope.app.component.tests.views.IC"
                attribute="index"
                permission="zope.Public"
                />
            '''
            ))

        v = zapi.getMultiAdapter((ob, request), name='test')
        self.assertEqual(v.index(), v)
        self.assert_(IBrowserPublisher.providedBy(v))
Ejemplo n.º 37
0
 def crumbs(self):
     try:
         myobjects = [self.context] + list(zapi.getParents(self.context))
     except Exception:
         myobjects = []
     myobjects.reverse()
     for myobject in myobjects:
         info = zapi.getMultiAdapter((myobject, self.request),
                                     IBreadcrumbInfo)
         if info.name == u'++etc++site':
             pass
         elif info.name == u'default':
             pass
         else:
             yield {
                 'name': info.name,
                 'url': info.url,
                 'active': info.active
             }
Ejemplo n.º 38
0
    def publishTraverse(self, request, name):
        """See zope.app.container.interfaces.IAdding"""
        if '=' in name:
            view_name, content_name = name.split("=", 1)
            self.contentName = content_name

            if view_name.startswith('@@'):
                view_name = view_name[2:]
            return zapi.getMultiAdapter((self, request), name=view_name)

        if name.startswith('@@'):
            view_name = name[2:]
        else:
            view_name = name

        view = zapi.queryView(self, view_name, request)
        if view is not None:
            return view

        factory = zapi.queryUtility(IFactory, name)
        if factory is None:
            return super(BasicAdding, self).publishTraverse(request, name)

        return factory
Ejemplo n.º 39
0
 def test_body_get_special(self):
     self._populate_special(self._obj)
     context = DummySetupEnviron()
     adapted = zapi.getMultiAdapter((self._obj, context), IBody)
     self.assertEqual(adapted.body,
                      _CATALOG_BODY % (_VOCABULARY_XML, _TEXT_XML))
Ejemplo n.º 40
0
    def singleBranchTree(self, root=''):
        """Return an XML document with the siblings and parents of an object.

        There is only one branch expanded, in other words, the tree is
        filled with the object, its siblings and its parents with
        their respective siblings.

        """
        result = ''
        oldItem = self.context
        try:
            oldItemOid = self.context.getObjectId()
        except:
            oldItemOid = "+++"

        vh = self.request.getVirtualHostRoot()
        if vh:
            print "vh: ", vh
            vhrootView = zapi.getMultiAdapter(
                    (vh, self.request), name='absolute_url')
            baseURL = vhrootView() + '/'
            try:
                rootName = '[' + vh.__name__ + ']'
            except:
                # we got the containment root itself as the virtual host
                # and there is no name.
                rootName = _('[top]')
            parents = getParentsFromContextToObject(self.context, vh)
        else:
            rootName = _('[top]')
            baseURL = self.request.getApplicationURL() + '/'
            parents = getParents(self.context)
        rootName = translate(rootName, context=self.request,
                             default=rootName)
        for item in parents:
            # skip skin if present
            if item == oldItem:
                continue
            if item is None:
                continue
            subItems = []
            if IReadContainer.providedBy(item):
                keys = list(item.keys())
            else:
                keys = []
            # include the site manager
            keys.append(u'++etc++site')
            for name in keys:
                # Only include items we can traverse to
                subItem = traverse(item, name, None)
                if subItem is None:
                    continue
                if name == u'++etc++site' and \
                   not checkPermission(\
                       'org.ict_ok.ikadmin_utils.usermanagement.Edit',
                       subItem):
                    continue
                iconUrl = self.getIconUrl(subItem)
                subitem_len = self.getLengthOf(subItem)
                dcAdapter = IGeneralDublinCore(subItem)
                xml_title = name
                if dcAdapter:
                    if dcAdapter.title:
                        xml_title = dcAdapter.title
                stateIconUrl = self.getStateIconUrl(subItem)
                if zapi.getParent(subItem):
                    item_ppath = zapi.canonicalPath(zapi.getParent(subItem)) \
                               + u'/'
                    item_ppath = item_ppath.replace('//', '/')
                else:
                    item_ppath = "/"
                try:
                    subItemOid = subItem.getObjectId()
                except:
                    subItemOid = "---"
                stateOverview = self.getStateOverview(item)
                if subitem_len > 0:
                    # the test below seems to be broken
                    # with the ++etc++site case
                    if subItem == oldItem:
                        if oldItemOid == subItemOid: # focussed
                            subItems.append(xmlEscapeWithCData(
                                u'<collection isfocus="" title=%s name=%s '
                                u'iklen=%s '
                                u'icon_url=%s expable="" state_url=%s '
                                u'path=%s state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                        else:
                            subItems.append(xmlEscapeWithCData(
                                u'<collection title=%s name=%s iklen=%s '
                                u'icon_url=%s state_url=%s path=%s '
                                u'state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                    else:
                        subItems.append(xmlEscape(
                            u'<collection title=%s name=%s iklen=%s '
                            u'icon_url=%s expable="" state_url=%s path=%s/>',
                            xml_title, name, subitem_len, iconUrl,
                            stateIconUrl, item_ppath))
                else:
                    if subItem == oldItem:
                        if oldItemOid == subItemOid: # focussed
                            subItems.append(xmlEscapeWithCData(
                                u'<collection isfocus="" title=%s '
                                u'name=%s iklen=%s '
                                u'icon_url=%s state_url=%s path=%s '
                                u'state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                        else:
                            subItems.append(xmlEscapeWithCData(
                                u'<collection title=%s name=%s iklen=%s '
                                u'icon_url=%s state_url=%s path=%s '
                                u'state_val=%s>%s</collection>', 
                                xml_title, name, subitem_len, iconUrl,
                                stateIconUrl, item_ppath, stateOverview,
                                result))
                    else:
                        subItems.append(xmlEscape(
                            u'<collection title=%s name=%s iklen=%s '
                            u'icon_url=%s state_url=%s path=%s/>',
                            xml_title, name, subitem_len, iconUrl,
                            stateIconUrl, item_ppath))

            result = u' '.join(subItems)
            oldItem = item

        # do not forget root folder
        iconUrl = self.getIconUrl(oldItem)
        xml_title = "ICT_Ok"
        rootName =  "."
        
        if len(result) > 0: # collection has content
            result = xmlEscapeWithCData(
                      u'<collection title=%s name=%s baseURL=%s iklen=%s '
                      u'icon_url=%s path=%s isroot="">%s</collection>',
                      xml_title, rootName, baseURL, len(oldItem), iconUrl,
                      "/", result)
        else:
            result = xmlEscapeWithCData(
                      u'<collection title=%s name=%s baseURL=%s iklen=%s '
                      u'icon_url=%s path=%s expable="" '
                      u'isroot="">%s</collection>',
                      xml_title, rootName, baseURL, len(oldItem), iconUrl,
                      "/", result)

        self.request.response.setHeader('Content-Type', 'text/xml')
        setNoCacheHeaders(self.request.response)
        title = translate(titleTemplate,
                          context=self.request, default=titleTemplate)
        loading = translate(loadingMsg,
                          context=self.request, default=loadingMsg)
        return xmlEscapeWithCData(
                u'<?xml version="1.0" encoding="ISO-8859-1"?>'
                u'<children title_tpl=%s title=%s '
                u'loading_msg=%s>%s</children>',
                title, title, loading, result)
Ejemplo n.º 41
0
 def test_node_get(self):
     self._populate(self._obj)
     context = DummySetupEnviron()
     adapted = zapi.getMultiAdapter((self._obj, context), INode)
     self.assertEqual(adapted.node.toprettyxml(' '), self._XML)
Ejemplo n.º 42
0
 def test_body_get(self):
     self._populate(self._obj)
     context = DummySetupEnviron()
     adapted = zapi.getMultiAdapter((self._obj, context), IBody)
     self.assertEqual(adapted.body, self._BODY)
Ejemplo n.º 43
0
 def render(self):
     url = zapi.getMultiAdapter( (self.context, self.request), IAbsoluteURL)
     return "<li>IAbsoluteUrl == %s</li>" % url