Example #1
0
 def test_publishTraverse_factory(self):
     factory = Factory()
     ztapi.provideUtility(IFactory, factory, 'foo')
     container = Container()
     request = TestRequest()
     adding = Adding(container, request)
     self.assert_(adding.publishTraverse(request, 'foo') is factory)
Example #2
0
    def setUp(self):
        super(TranslateTest, self).setUp()

        # Setup the registries
        ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets,
                             HTTPCharsets)

        ztapi.provideUtility(IFactory, Factory(MessageCatalog),
                             'zope.app.MessageCatalog')

        domain = TranslationDomain()
        domain.domain = 'default'

        en_catalog = MessageCatalog('en', 'default')
        de_catalog = MessageCatalog('de', 'default')

        en_catalog.setMessage('short_greeting', 'Hello!')
        de_catalog.setMessage('short_greeting', 'Hallo!')

        en_catalog.setMessage('greeting', 'Hello $name, how are you?')
        de_catalog.setMessage('greeting', 'Hallo $name, wie geht es Dir?')

        domain['en-1'] = en_catalog
        domain['de-1'] = de_catalog

        self._view = Translate(domain, self._getRequest())
Example #3
0
 def test_publishTraverse_factory(self):
     factory = Factory()
     ztapi.provideUtility(IFactory, factory, 'foo')
     container = Container()
     request = TestRequest()
     adding = Adding(container, request)
     self.assert_(adding.publishTraverse(request, 'foo') is factory)
Example #4
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)
Example #5
0
def sessionSetUp(session_data_container_class=PersistentSessionDataContainer):
    placelesssetup.setUp()
    ztapi.provideAdapter(IRequest, IClientId, TestClientId)
    ztapi.provideAdapter(IRequest, ISession, Session)
    ztapi.provideUtility(IClientIdManager, CookieClientIdManager())
    sdc = session_data_container_class()
    ztapi.provideUtility(ISessionDataContainer, sdc, '')
Example #6
0
def sessionSetUp(session_data_container_class=PersistentSessionDataContainer):
    placelesssetup.setUp()
    ztapi.provideAdapter(IRequest, IClientId, TestClientId)
    ztapi.provideAdapter(IRequest, ISession, Session)
    ztapi.provideUtility(IClientIdManager, CookieClientIdManager())
    sdc = session_data_container_class()
    ztapi.provideUtility(ISessionDataContainer, sdc, '')
Example #7
0
    def setUp(self):
        self.buildFolders()

        ztapi.provideAdapter(IAnnotations, IPrincipalClipboard,
                             PrincipalClipboard)
        ztapi.provideUtility(IPrincipalAnnotationUtility,
                             PrincipalAnnotationUtility())
 def setUp(self):
     setUp()
     from bibliograph.rendering.interfaces import IBibTransformUtility
     from bibliograph.rendering.utility import ExternalTransformUtility
     ztapi.provideUtility(IBibTransformUtility,
                          ExternalTransformUtility(),
                          name=u'external')
Example #9
0
    def testProtectedPageViews(self):
        ztapi.provideUtility(IPermission, Permission('p', 'P'), 'p')

        request = TestRequest()
        self.assertEqual(
            component.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 = component.getMultiAdapter((ob, request), name='index.html')
        v = ProxyFactory(v)
        zope.security.management.getInteraction().add(request)
        self.assertRaises(Exception, v)
        v = component.getMultiAdapter((ob, request), name='action.html')
        v = ProxyFactory(v)
        self.assertRaises(Exception, v)
    def setUp(self):
        self.parser = EndNoteParser()

        from bibliograph.rendering.interfaces import IBibTransformUtility
        from bibliograph.rendering.utility import ExternalTransformUtility    
        ztapi.provideUtility(IBibTransformUtility, ExternalTransformUtility(),
                             name=u'external')
Example #11
0
def nonHTTPSessionTestCaseSetUp(sdc_class=PersistentSessionDataContainer):
    # I am getting an error with ClientId and not TestClientId
    placelesssetup.setUp()
    ztapi.provideAdapter(IRequest, IClientId, ClientId)
    ztapi.provideAdapter(IRequest, ISession, Session)
    ztapi.provideUtility(IClientIdManager, CookieClientIdManager())
    sdc = sdc_class()
    ztapi.provideUtility(ISessionDataContainer, sdc, '')
Example #12
0
def nonHTTPSessionTestCaseSetUp(sdc_class=PersistentSessionDataContainer):
    # I am getting an error with ClientId and not TestClientId
    placelesssetup.setUp()
    ztapi.provideAdapter(IRequest, IClientId, ClientId)
    ztapi.provideAdapter(IRequest, ISession, Session)
    ztapi.provideUtility(IClientIdManager, CookieClientIdManager())
    sdc = sdc_class()
    ztapi.provideUtility(ISessionDataContainer, sdc, '')
Example #13
0
 def setUp(self):
     super(Test, self).setUp()
     ztapi.provideAdapter(IAttributeAnnotatable, IAnnotations,
                          AttributeAnnotations)
     ztapi.provideAdapter(IAnnotatable, ICacheable,
                          AnnotationCacheable)
     self._cache = CacheStub()
     ztapi.provideUtility(ICache, self._cache, "my_cache")
    def setUp(self):
        classImplements(TranslationDomain, IAttributeAnnotatable)
        self.sm = PlacefulSetup.setUp(self, site=True)
        TestITranslationDomain.setUp(self)

        setup.addUtility(self.sm, "default", ITranslationDomain, self._domain)

        ztapi.provideUtility(IFactory, Factory(MessageCatalog), "zope.app.MessageCatalog")
Example #15
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)
Example #16
0
 def setUp(self):
     super(Test, self).setUp()
     self.request = TestRequest()
     self.undo = TestIUndoManager()
     ztapi.provideUtility(IUndoManager, self.undo)
     principalRegistry.definePrincipal('monkey', 'Monkey Patch',
                                       login='******')
     principalRegistry.definePrincipal('bonobo', 'Bonobo Abdul-Fasil',
                                       login='******')
Example #17
0
 def setUp(self):
     super(Test, self).setUp()
     TestII18nAware.setUp(self)
     ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets,
                          HTTPCharsets)
     ztapi.provideAdapter(IHTTPRequest, IUserPreferredLanguages,
                          BrowserLanguages)
     # Setup the negotiator utility
     ztapi.provideUtility(INegotiator, negotiator)
Example #18
0
 def setUp(self):
     super(Test, self).setUp()
     TestII18nAware.setUp(self)
     ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets,
                          HTTPCharsets)
     ztapi.provideAdapter(IHTTPRequest, IUserPreferredLanguages,
                          BrowserLanguages)
     # Setup the negotiator utility
     ztapi.provideUtility(INegotiator, negotiator)
Example #19
0
def setUp(session_data_container_class=PersistentSessionDataContainer):
    placelesssetup.setUp()
    ztapi.provideAdapter(IRequest, IClientId, ClientId)
    ztapi.provideAdapter(IRequest, ISession, Session)
    ztapi.provideUtility(IClientIdManager, CookieClientIdManager())
    sdc = session_data_container_class()
    for product_id in ('', 'products.foo', 'products.bar', 'products.baz'):
        ztapi.provideUtility(ISessionDataContainer, sdc, product_id)
    request = HTTPRequest(StringIO(), {}, None)
    return request
Example #20
0
    def setUp(self):
        super(DirectivesTest, self).setUp()
        self.testMailer = Mailer()

        ztapi.provideUtility(IMailer, Mailer(), name="test.smtp")
        ztapi.provideUtility(IMailer, self.testMailer, name="test.mailer")

        self.context = xmlconfig.file("mail.zcml", zope.app.mail.tests)
        self.orig_maildir = delivery.Maildir
        delivery.Maildir = MaildirStub
Example #21
0
 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()
Example #22
0
    def setUp(self):
        super(TestGettextExportImport, self).setUp()

        # Setup the negotiator utility
        ztapi.provideUtility(INegotiator, negotiator)

        self._domain = TranslationDomain()
        self._domain.domain = 'default'
        ztapi.provideUtility(IFactory, Factory(MessageCatalog),
                             'zope.app.MessageCatalog')
Example #23
0
def setUp(test):
    root_folder = setup.placefulSetUp(True)
    ztapi.provideAdapter(None, IUniqueId, LocationUniqueId)
    ztapi.provideAdapter(None, IPhysicallyLocatable,
                         LocationPhysicallyLocatable)

    # Set up apidoc module
    test.globs['apidoc'] = APIDocumentation(root_folder, '++apidoc++')

    # Register documentation modules
    ztapi.provideUtility(IDocumentationModule, UtilityModule(), 'Utility')
Example #24
0
    def test(self):
        functional.BrowserTestCase.setUp(self)
        
        root = self.getRootFolder()._p_jar.root()
        appkey = 'zope.app.generations.demo'
        root[generations_key][appkey] = 0
        self.commit()
        manager = SchemaManager(0, 3, 'zope.app.generations.demo')

        ztapi.provideUtility(ISchemaManager, manager, appkey)

        response = self.publish('/++etc++process/@@generations.html',
                                basic='globalmgr:globalmgrpw')
        body = response.getBody()
        body = ' '.join(body.split())
        expect = ('zope.app.generations.demo</a> </td> '
                  '<td>0</td> <td>3</td> <td>0</td> '
                  '<td> <input type="submit" value=" evolve " '
                  'name="evolve-app-zope.app.generations.demo"> </td>')
        self.assert_(body.find(expect) > 0)

        response = self.publish('/++etc++process/@@generations.html'
                                '?evolve-app-zope.app.generations.demo=evolve',
                                basic='globalmgr:globalmgrpw')
        body = response.getBody()
        body = ' '.join(body.split())
        expect = ('zope.app.generations.demo</a> </td> '
                  '<td>0</td> <td>3</td> <td>1</td> '
                  '<td> <input type="submit" value=" evolve " '
                  'name="evolve-app-zope.app.generations.demo"> </td>')
        self.assert_(body.find(expect) > 0)

        response = self.publish('/++etc++process/@@generations.html'
                                '?evolve-app-zope.app.generations.demo=evolve',
                                basic='globalmgr:globalmgrpw')
        body = response.getBody()
        body = ' '.join(body.split())
        expect = ('zope.app.generations.demo</a> </td> '
                  '<td>0</td> <td>3</td> <td>2</td> '
                  '<td> <input type="submit" value=" evolve " '
                  'name="evolve-app-zope.app.generations.demo"> </td>')
        self.assert_(body.find(expect) > 0)

        response = self.publish('/++etc++process/@@generations.html'
                                '?evolve-app-zope.app.generations.demo=evolve',
                                basic='globalmgr:globalmgrpw')
        body = response.getBody()
        body = ' '.join(body.split())
        expect = ('zope.app.generations.demo</a> </td> '
                  '<td>0</td> <td>3</td> <td>3</td> '
                  '<td> <span>')
        self.assert_(body.find(expect) > 0)

        ztapi.unprovideUtility(ISchemaManager, appkey)
Example #25
0
    def setUp(self):
        super(TestLockStorage, self).setUp()
        setup.placelessSetUp()
        zope.security.management.endInteraction()

        ztapi.provideAdapter(Interface, IKeyReference, FakeKeyReference)
        ztapi.provideAdapter(Interface, ILockable, LockingAdapterFactory)
        ztapi.provideAdapter(None, IPathAdapter, LockingPathAdapter, "locking")

        self.storage = storage = PersistentLockStorage()
        ztapi.provideUtility(ILockStorage, storage)
        ztapi.provideUtility(ILockTracker, storage)
Example #26
0
    def setUp(self):
        PlacefulSetup.setUp(self)
        PlacefulSetup.buildFolders(self)
        ztapi.provideAdapter(IContained, IObjectCopier, ObjectCopier)
        ztapi.provideAdapter(IContained, IObjectMover, ObjectMover)
        ztapi.provideAdapter(IContainer, IContainerItemRenamer,
            ContainerItemRenamer)

        ztapi.provideAdapter(IAnnotations, IPrincipalClipboard,
                             PrincipalClipboard)
        ztapi.provideUtility(IPrincipalAnnotationUtility,
                             PrincipalAnnotationUtility())
Example #27
0
    def testAction(self):
        # make a private factory
        ztapi.provideUtility(IFactory, Factory(), 'fooprivate')

        factory = Factory()
        factory.__Security_checker__ = zope.security.checker.NamesChecker(
            ['__call__'])
        ztapi.provideUtility(IFactory, factory, 'foo')

        container = Container()
        adding = Adding(container, TestRequest())
        adding.nextURL = lambda: '.'
        adding.nameAllowed = lambda: True

        # we can't use a private factory:
        self.assertRaises(ForbiddenAttribute,
                          adding.action,
                          type_name='fooprivate',
                          id='bar')

        # typical add - id is provided by user
        adding.action(type_name='foo', id='bar')
        self.assert_('bar' in container)

        # missing type_name
        self.assertRaises(UserError, adding.action, id='bar')

        # missing id
        self.assertRaises(KeyError, adding.action, type_name='foo')

        # bad type_name
        self.assertRaises(ComponentLookupError,
                          adding.action,
                          type_name='***',
                          id='bar')

        # alternative add - id is provided internally instead of from user
        adding.nameAllowed = lambda: False
        adding.contentName = 'baz'
        adding.action(type_name='foo')
        self.assert_('baz' in container)

        # alternative add w/missing contentName
        # Note: Passing is None as object name might be okay, if the container
        #       is able to hand out ids itself. Let's not require a content
        #       name to be specified!
        # For the container, (or really, the chooser, to choose, we have to
        # marke the container as a ContainerNamesContainer
        directlyProvides(container, IContainerNamesContainer)
        adding.contentName = None
        adding.action(type_name='foo')
        self.assert_('Content' in container)
 def setUp(self):
     PlacefulSetup.setUp(self)
     defineRole('manager', Message('Manager', 'testdomain'))
     defineRole('member',  Message('Member', 'testdomain'))
     definePermission('read', Message('Read', 'testdomain'))
     definePermission('write', Message('Write', 'testdomain'))
     site = RolePermissionManager()
     self.view = RolePermissionView(FakeSiteManager(site), None)
     ztapi.provideUtility(ITranslationDomain,
                          TranslationDomain(Member="A Member",
                                            Write="A Write",
                                            ),
                          'testdomain')
def workflowSetUp(doctest):
    placelesssetup.setUp()
    ztapi.provideAdapter(annotation_interfaces.IAnnotatable,
                         interfaces.IWorkflowState,
                         workflow.WorkflowState)
    ztapi.provideAdapter(annotation_interfaces.IAnnotatable,
                         interfaces.IWorkflowInfo,
                         workflow.WorkflowInfo)
    ztapi.provideAdapter(annotation_interfaces.IAttributeAnnotatable,
                         annotation_interfaces.IAnnotations,
                         attribute.AttributeAnnotations)
    ztapi.provideUtility(interfaces.IWorkflowVersions,
                         WorkflowVersions())
Example #30
0
def setUp(test):
    placelesssetup.setUp()
    # Register Renderer Components
    ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory,
                         'zope.source.rest')
    ztapi.browserView(IReStructuredTextSource, '',
                      ReStructuredTextToHTMLRenderer)
    # Cheat and register the ReST renderer as the STX one as well.
    ztapi.provideUtility(IFactory, ReStructuredTextSourceFactory,
                         'zope.source.stx')
    ztapi.browserView(IReStructuredTextSource, '',
                      ReStructuredTextToHTMLRenderer)
    setup.setUpTestAsModule(test, 'zope.app.apidoc.doctest')
Example #31
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)
Example #32
0
def setUp(test):
    placelesssetup.setUp()
    setup.setUpTraversal()
    
    ztapi.provideAdapter(IInterface, IUniqueId, LocationUniqueId)

    # 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')    
Example #33
0
def setUp(test):
    ps.setUp()
    dict = test.globs
    dict.clear()
    dict['__name__'] = name
    sys.modules[name] = FakeModule(dict)

    ztapi.provideAdapter(Interface, IKeyReference, maybeFakeKeyReference)
    ztapi.provideAdapter(Interface, ILockable, LockingAdapterFactory)
    ztapi.provideAdapter(None, IPathAdapter, LockingPathAdapter, "locking")
    storage = PersistentLockStorage()
    ztapi.provideUtility(ILockStorage, storage)
    ztapi.provideUtility(ILockTracker, storage)
    test._storage = storage  # keep-alive
 def testTraverseNameApplicationControl(self):
     from zope.app.applicationcontrol.applicationcontrol \
          import applicationController, applicationControllerRoot
     from zope.traversing.interfaces import IEtcNamespace
     ztapi.provideUtility(IEtcNamespace, applicationController, 'process')
     pub = self.klass(self.db)
     r = self._createRequest('/++etc++process',pub)
     ac = pub.traverseName(r,
                           applicationControllerRoot,
                           '++etc++process')
     self.assertEqual(ac, applicationController)
     r = self._createRequest('/++etc++process',pub)
     app = r.publication.getApplication(r)
     self.assertEqual(app, applicationControllerRoot)
Example #35
0
    def testAction(self):
        # make a private factory
        ztapi.provideUtility(IFactory, Factory(), 'fooprivate')

        factory = Factory()
        factory.__Security_checker__ = zope.security.checker.NamesChecker(
            ['__call__'])
        ztapi.provideUtility(IFactory, factory, 'foo')

        container = Container()
        adding = Adding(container, TestRequest())
        adding.nextURL = lambda: '.'
        adding.nameAllowed = lambda: True

        # we can't use a private factory:
        self.assertRaises(ForbiddenAttribute,
                          adding.action, type_name='fooprivate', id='bar')

        # typical add - id is provided by user
        adding.action(type_name='foo', id='bar')
        self.assert_('bar' in container)

        # missing type_name
        self.assertRaises(UserError, adding.action, id='bar')

        # missing id
        self.assertRaises(KeyError, adding.action, type_name='foo')

        # bad type_name
        self.assertRaises(ComponentLookupError, adding.action,
            type_name='***', id='bar')

        # alternative add - id is provided internally instead of from user
        adding.nameAllowed = lambda: False
        adding.contentName = 'baz'
        adding.action(type_name='foo')
        self.assert_('baz' in container)

        # alternative add w/missing contentName
        # Note: Passing is None as object name might be okay, if the container
        #       is able to hand out ids itself. Let's not require a content
        #       name to be specified!
        # For the container, (or really, the chooser, to choose, we have to
        # marke the container as a ContainerNamesContainer
        directlyProvides(container, IContainerNamesContainer)
        adding.contentName = None
        adding.action(type_name='foo')
        self.assert_('Content' in container)
Example #36
0
    def testGlobalAuth(self):
        # Replace the global registry with a stub that doesn't return an
        # unauthenticated principal.
        authentication = AuthUtility3()
        ztapi.provideUtility(IAuthentication, authentication)

        # We need a fallback unauthenticated principal, otherwise we'll get a
        # ComponentLookupError:
        self.assertRaises(ComponentLookupError,
                          self.publication.beforeTraversal, self.request)

        # Let's register an unauthenticated principal instance for the lookup:
        principal = UnauthenticatedPrincipal('fallback')
        ztapi.provideUtility(IFallbackUnauthenticatedPrincipal, principal)
        self.publication.beforeTraversal(self.request)
        self.failUnless(self.request.principal is principal)
Example #37
0
    def testGlobalAuth(self):
        # Replace the global registry with a stub that doesn't return an
        # unauthenticated principal.
        authentication = AuthUtility3()
        ztapi.provideUtility(IAuthentication, authentication)

        # We need a fallback unauthenticated principal, otherwise we'll get a
        # ComponentLookupError:
        self.assertRaises(ComponentLookupError,
                          self.publication.beforeTraversal, self.request)

        # Let's register an unauthenticated principal instance for the lookup:
        principal = UnauthenticatedPrincipal('fallback')
        ztapi.provideUtility(IFallbackUnauthenticatedPrincipal, principal)
        self.publication.beforeTraversal(self.request)
        self.failUnless(self.request.principal is principal)
Example #38
0
 def testInvalidate(self):
     # Test that setting a different cache ID invalidates the old cached
     # value
     cache1 = CacheStub()
     ztapi.provideUtility(ICache, cache1, "cache1")
     cache2 = CacheStub()
     ztapi.provideUtility(ICache, cache2, "cache2")
     ob = ObjectStub()
     adapter = AnnotationCacheable(ob)
     adapter.setCacheId('cache1')
     self.assertEquals(cache1.invalidated, [],
                       "called invalidate too early")
     adapter.setCacheId('cache2')
     self.assertEquals(cache1.invalidated, [ob], "did not call invalidate")
     adapter.setCacheId('cache2')
     self.assertEquals(
         cache2.invalidated, [],
         "called invalidate when reassigning to the same cache")
Example #39
0
    def setUp(self):
        super(DirectivesTest, self).setUp()
        ztapi.provideUtility(IPermission, Permission('zope.View', 'View', ''),
                             'zope.View')
        XMLConfig('meta.zcml', zope.app.security)()
        XMLConfig('meta.zcml', zope.app.component)()
        XMLConfig('meta.zcml', zope.app.onlinehelp)()
        ztapi.provideAdapter(None, ITraverser, Traverser)
        ztapi.provideAdapter(None, ITraversable, DefaultTraversable)
        ztapi.provideAdapter(None, IPhysicallyLocatable,
                             LocationPhysicallyLocatable)

        default = Factory(OnlineHelpTopic)
        rest = Factory(RESTOnlineHelpTopic)
        stx = Factory(STXOnlineHelpTopic)
        zpt = Factory(ZPTOnlineHelpTopic)
        ztapi.provideUtility(IFactory, default, 'onlinehelp.topic.default')
        ztapi.provideUtility(IFactory, rest, 'onlinehelp.topic.rest')
        ztapi.provideUtility(IFactory, stx, 'onlinehelp.topic.stx')
        ztapi.provideUtility(IFactory, zpt, 'onlinehelp.topic.zpt')
Example #40
0
def setUp(test):
    root_folder = setup.placefulSetUp(True)

    ztapi.provideAdapter(None, IUniqueId, LocationUniqueId)
    ztapi.provideAdapter(None, IPhysicallyLocatable,
                         LocationPhysicallyLocatable)

    # Set up apidoc module
    test.globs['apidoc'] = APIDocumentation(root_folder, '++apidoc++')

    # Register documentation modules
    ztapi.provideUtility(IDocumentationModule, ZCMLModule(), 'ZCML')

    config_file = os.path.join(
        os.path.dirname(zope.app.zcmlfiles.__file__), 'meta.zcml')

    # Fix up path for tests.
    global old_context
    old_context = zope.app.appsetup.appsetup.getConfigContext()
    zope.app.appsetup.appsetup.__config_context = xmlconfig.file(
        config_file, zope.app.zcmlfiles, execute=False)
Example #41
0
    def setUp(self):
        super(BasePublicationTests, self).setUp()
        from zope.security.management import endInteraction
        endInteraction()
        ztapi.provideAdapter(IHTTPRequest, IUserPreferredCharsets,
                             HTTPCharsets)
        self.policy = setSecurityPolicy(
            simplepolicies.PermissiveSecurityPolicy)
        self.storage = DemoStorage('test_storage')
        self.db = db = DB(self.storage)

        ztapi.provideUtility(IAuthentication, principalRegistry)

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

        if app is None:
            from zope.app.folder import rootFolder
            app = rootFolder()
            root[ZopePublication.root_name] = app
            transaction.commit()

        connection.close()
        self.app = app

        from zope.traversing.namespace import view, resource, etc
        ztapi.provideNamespaceHandler('view', view)
        ztapi.provideNamespaceHandler('resource', resource)
        ztapi.provideNamespaceHandler('etc', etc)

        self.request = TestRequest('/f1/f2')
        self.user = Principal('test.principal')
        self.request.setPrincipal(self.user)
        from zope.interface import Interface
        self.presentation_type = Interface
        self.request._presentation_type = self.presentation_type
        self.object = object()
        self.publication = ZopePublication(self.db)
Example #42
0
    def test_create_content_factory_id(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 "."

        # register content factory for content factory id lookup
        ztapi.provideAdapter(None, IComponentLookup, SiteManagerAdapter)
        ztapi.provideUtility(IFactory, Factory(C), name='C')

        adding = Adding(self)
        self._invoke_add(content_factory='C')
        (descriminator, callable, args, kw) = self._context.last_action
        factory = AddViewFactory(*args)
        request = TestRequest()
        view = 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'})
Example #43
0
    def test_scrubHTML_with_adapter(self):
        from zope.interface import implements
        from zope.component.testing import setUp
        from zope.component.testing import tearDown
        from zope.app.testing import ztapi
        from Products.CMFDefault.interfaces import IHTMLScrubber
        from Products.CMFDefault.utils import scrubHTML

        class _Scrubber:
            implements(IHTMLScrubber)

            def scrub(self, html):
                return html.upper()

        setUp()
        try:
            ztapi.provideUtility(IHTMLScrubber, _Scrubber())
            self.assertEqual(scrubHTML('<a href="foo.html">bar</a>'),
                             '<A HREF="FOO.HTML">BAR</A>')
            self.assertEqual(scrubHTML('<b>bar</b>'), '<B>BAR</B>')
            self.assertEqual(scrubHTML('<base href="" /><base>'),
                             '<BASE HREF="" /><BASE>')
            self.assertEqual(scrubHTML('<blockquote>bar</blockquote>'),
                             '<BLOCKQUOTE>BAR</BLOCKQUOTE>')
            self.assertEqual(scrubHTML('<body bgcolor="#ffffff">bar</body>'),
                             '<BODY BGCOLOR="#FFFFFF">BAR</BODY>')
            self.assertEqual(scrubHTML('<br /><br>'), '<BR /><BR>')
            self.assertEqual(scrubHTML('<hr /><hr>'), '<HR /><HR>')
            self.assertEqual(scrubHTML('<img src="foo.png" /><img>'),
                             '<IMG SRC="FOO.PNG" /><IMG>')
            self.assertEqual(
                scrubHTML('<meta name="title" content="" /><meta>'),
                '<META NAME="TITLE" CONTENT="" /><META>')

        finally:
            tearDown()
Example #44
0
def setUpZope(test):
    zope.component.eventtesting.setUp(test)
    zope.component.provideAdapter(AttributeAnnotations)
    # The auth tests require available password managers:
    ztapi.provideUtility(IPasswordManager, PlainTextPasswordManager(),
                                  "Plain Text")
    ztapi.provideUtility(IPasswordManager, MD5PasswordManager(),
                                  "MD5")
    ztapi.provideUtility(IPasswordManager, SHA1PasswordManager(),
                                  "SHA1")
Example #45
0
        if not mountpoint:
            return []
        return mountpoint.objectValues('Plone Site')

    def install(self, context):
        root = context.connection.root()
        app = root['Application']
        portals = self.get_portals(app)

        for portal in portals:
            portal.portal_javascripts.cache_duration = 14
            portal.portal_css.cache_duration = 14
            portal.portal_kss.cache_duration = 14

        transaction.commit()

    def evolve(self, context, generation):
        root = context.connection.root()
        app = root['Application']
        portals = self.get_portals(app)

        if generation == 1:
            for portal in portals:
                pass

        transaction.commit()


manager = PortalUpdateManager()
ztapi.provideUtility(ISchemaManager, manager, name='osha.policy')
    def test_interface_search(self):

        ztapi.provideUtility(IDummy, Dummy)
        result = RegistryInfoUtility().getRegistrationsForInterface(
            'Dummy', types=['utilities'])
        self.failUnless(len(result) == 1)
Example #47
0
def registerAddMenu():
    ztapi.provideUtility(IMenuItemType, AddMenu, 'zope.app.container.add')
    ztapi.provideUtility(IBrowserMenu,
                         BrowserMenu('zope.app.container.add', u'', u''),
                         'zope.app.container.add')
def setUp(test):
    ztapi.provideUtility(zc.table.interfaces.IFormatterFactory,
                         SimpleFormatter)
    assert component.getUtility(zc.table.interfaces.IFormatterFactory) != None
Example #49
0
 def setUp(self):
     ztapi.provideUtility(IPasswordManager, PlainTextPasswordManager(),
                          "Plain Text")
     ztapi.provideUtility(IPasswordManager, MD5PasswordManager(), "MD5")
     ztapi.provideUtility(IPasswordManager, SHA1PasswordManager(), "SHA1")