Example #1
0
    def test_schema_lookup(self):
        
        # Context and request
        
        context_mock = self.create_dummy(portal_type=u'testtype')
        request_mock = self.create_dummy()
        
        # FTI
        
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ISchema)
        self.expect(fti_mock.behaviors).result((IBehaviorOne.__identifier__, 
                                                IBehaviorTwo.__identifier__, 
                                                IBehaviorThree.__identifier__))
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")
      
        # Form
        
        self.replay()
        
        view = DefaultView(context_mock, request_mock)
        
        self.assertEquals(ISchema, view.schema)
        self.assertEquals([IBehaviorOne, IBehaviorTwo], list(view.additionalSchemata,))

        # When we register our own IBehaviorAssignable we can
        # influence what goes into the additionalSchemata:
        provideAdapter(NoBehaviorAssignable)
        self.assertEquals([], list(view.additionalSchemata,))
Example #2
0
 def test_with_adapter(self):
     
     class DummyView(object):
         implements(IView)
         
         def __init__(self, context, request):
             self.context = context
             self.request = request
     
     class DummyContext(object):
         pass
     
     class DummyRequest(dict):
         pass
     
     class DummyLastModified(object):
         implements(ILastModified)
         adapts(DummyContext)
         
         def __init__(self, context):
             self.context = context
             self.request = request
     
     provideAdapter(DummyLastModified)
     
     context = DummyContext()
     request = DummyRequest()
     
     view = DummyView(context, request)
     
     lastModified = ILastModified(view)
     self.failUnless(isinstance(lastModified, DummyLastModified,))
     
     self.assertEquals(context, lastModified.context)
     self.assertEquals(request, lastModified.request)
 def setUp(self):
     self.setUpContent()
     self.request = TestRequest()
     self.widget = self._WidgetFactory(
         self.field, self.field.value_type, self.request)
     provideAdapter(DisplayWidget, (ITextLine, IDefaultBrowserLayer),
                    IDisplayWidget)
Example #4
0
    def test_dont_swallow_conflict_error(self):

        @implementer(IRulesetLookup)
        @adapter(Interface, Interface)
        class DummyRulesetLookup(object):

            def __init__(self, published, request):
                self.published = published
                self.request = request

            def __call__(self):
                raise ConflictError()

        provideAdapter(DummyRulesetLookup)

        provideUtility(Registry(), IRegistry)
        registry = getUtility(IRegistry)
        registry.registerInterface(ICacheSettings)
        settings = registry.forInterface(ICacheSettings)
        settings.enabled = True
        settings.operationMapping = {'foo': 'bar'}

        view = DummyView()
        request = DummyRequest(view, DummyResponse())
        self.assertRaises(ConflictError, intercept, DummyEvent(request))
Example #5
0
    def setUp(self):
        provideAdapter(persistentFieldAdapter)
        self.registry = Registry()
        self.registry.registerInterface(ICachePurgingSettings)
        provideUtility(self.registry, IRegistry)

        self.settings = self.registry.forInterface(ICachePurgingSettings)
        self.settings.enabled = True
        self.settings.cachingProxies = ('http://localhost:1234',)

        @implementer(IPurgePaths)
        @adapter(FauxContext)
        class FauxPurgePaths(object):

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

            def getRelativePaths(self):
                return ['/foo', '/bar']

            def getAbsolutePaths(self):
                return []

        provideAdapter(FauxPurgePaths, name="test1")

        @implementer(IPurger)
        class FauxPurger(object):

            def purgeSync(self, url, httpVerb='PURGE'):
                return "200 OK", "cached", None

        provideUtility(FauxPurger())
Example #6
0
    def test_locale_property_accessor(self):
        from zope.component import provideAdapter
        from zope.publisher.browser import BrowserLanguages
        from zope.publisher.interfaces.http import IHTTPRequest
        from zope.i18n.interfaces import IUserPreferredLanguages
        from zope.i18n.interfaces.locales import ILocale
        from ZPublisher.HTTPRequest import _marker

        provideAdapter(BrowserLanguages, [IHTTPRequest],
                       IUserPreferredLanguages)

        env = {'HTTP_ACCEPT_LANGUAGE': 'en'}
        request = self._makeOne(environ=env)

        # before accessing request.locale for the first time, request._locale
        # is still a marker
        self.assert_(request._locale is _marker)

        # when accessing request.locale we will see an ILocale
        self.assert_(ILocale.providedBy(request.locale))

        # and request._locale has been set
        self.assert_(request._locale is request.locale)

        # It won't be available through dictonary lookup, though
        self.assert_(request.get('locale') is None)
Example #7
0
    def test_locale_semantics(self):
        from zope.component import provideAdapter
        from zope.publisher.browser import BrowserLanguages
        from zope.publisher.interfaces.http import IHTTPRequest
        from zope.i18n.interfaces import IUserPreferredLanguages
        from zope.i18n.interfaces.locales import ILocale

        provideAdapter(BrowserLanguages, [IHTTPRequest],
                       IUserPreferredLanguages)
        env_ = {'HTTP_ACCEPT_LANGUAGE': 'en'}

        # we should also test the correct semantics of the locale
        for httplang in ('it', 'it-ch', 'it-CH', 'IT', 'IT-CH', 'IT-ch'):
            env = env_.copy()
            env['HTTP_ACCEPT_LANGUAGE'] = httplang
            request = self._makeOne(environ=env)
            locale = request.locale
            self.assert_(ILocale.providedBy(locale))
            parts = httplang.split('-')
            lang = parts.pop(0).lower()
            territory = variant = None
            if parts:
                territory = parts.pop(0).upper()
            if parts:
                variant = parts.pop(0).upper()
            self.assertEqual(locale.id.language, lang)
            self.assertEqual(locale.id.territory, territory)
            self.assertEqual(locale.id.variant, variant)
Example #8
0
 def test_abort(self):
     
     class Transform1(object):
         implements(ITransform)
         adapts(Interface, Interface)
         
         order = 0
         
         def __init__(self, published, request):
             self.published = published
             self.request = request
         
         def transformBytes(self, result, encoding):
             return None
             
         def transformUnicode(self, result, encoding):
             return None
         
         def transformIterable(self, result, encoding):
             return None
     
     provideAdapter(Transform1, name=u"test.one")
     
     published = FauxPublished()
     request = FauxRequest(published)
     result = ["Blah"]
     encoding = 'utf-8'
     
     new_result = self.t(request, result, encoding)
     self.assertEquals(["Blah"], new_result)
Example #9
0
 def test_off_switch(self):
     
     class Transform1(object):
         implements(ITransform)
         adapts(Interface, Interface)
         
         order = 0
         
         def __init__(self, published, request):
             self.published = published
             self.request = request
         
         def transformBytes(self, result, encoding):
             return result + " transformed"
             
         def transformUnicode(self, result, encoding):
             return result + u" transformed"
         
         def transformIterable(self, result, encoding):
             return ''.join(result) + ' transformed'
     
     provideAdapter(Transform1, name=u"test.one")
     
     published = FauxPublished()
     request = FauxRequest(published)
     request.environ['plone.transformchain.disable'] = True
     
     result = ["Blah"]
     encoding = 'utf-8'
     
     new_result = self.t(request, result, encoding)
     self.assertEquals(None, new_result)
Example #10
0
 def setUp(self):
     from Products.Reflecto.catalog import \
         FileProxyIndexableContentAdapter
     self.reflector = MockReflector()
     provideAdapter(FileProxyIndexableContentAdapter) 
     getGlobalSiteManager().registerUtility(FakeConverter, IConverter,
             'image/jpeg')
    def test_anonymous_can_not_add_comments_if_discussion_is_not_allowed(self):
        """Make sure that anonymous users can't post comments if anonymous
           comments are disabled.
        """

        # Anonymous comments are disabled by default

        logout()

        def make_request(form={}):
            request = TestRequest()
            request.form.update(form)
            alsoProvides(request, IFormLayer)
            alsoProvides(request, IAttributeAnnotatable)
            return request

        provideAdapter(adapts=(Interface, IBrowserRequest),
                       provides=Interface,
                       factory=CommentForm,
                       name=u"comment-form")

        request = make_request(form={'form.widgets.text': u'bar'})

        commentForm = getMultiAdapter((self.context, request),
                                      name=u"comment-form")
        commentForm.update()
        data, errors = commentForm.extractData()  # pylint: disable-msg=W0612

        self.assertEqual(len(errors), 0)
        self.assertRaises(
            Unauthorized,
            commentForm.handleComment,
            commentForm,
            "foo"
        )
Example #12
0
    def test_CatalogCounter(self):
        from plone.app.caching.operations.etags import CatalogCounter

        class DummyCatalog(object):

            def getCounter(self):
                return 10

        class DummyTools(object):
            implements(Interface)
            adapts(DummyContext, Interface)

            def __init__(self, context, request):
                pass

            def catalog(self):
                return DummyCatalog()

        provideAdapter(DummyTools, name=u"plone_tools")

        environ = {'SERVER_NAME': 'example.com', 'SERVER_PORT': '80'}
        response = HTTPResponse()
        request = HTTPRequest(StringIO(), environ, response)
        published = DummyPublished(DummyContext())

        etag = CatalogCounter(published, request)

        self.assertEqual('10', etag())
Example #13
0
    def test_UserID_member(self):
        from plone.app.caching.operations.etags import UserID

        class DummyMember(object):

            def getId(self):
                return 'bob'

        class DummyPortalState(object):
            implements(Interface)
            adapts(DummyContext, Interface)

            def __init__(self, context, request):
                pass

            def member(self):
                return DummyMember()

        provideAdapter(DummyPortalState, name=u"plone_portal_state")

        environ = {'SERVER_NAME': 'example.com', 'SERVER_PORT': '80'}
        response = HTTPResponse()
        request = HTTPRequest(StringIO(), environ, response)
        published = DummyPublished(DummyContext())

        etag = UserID(published, request)

        self.assertEqual('bob', etag())
Example #14
0
    def test_Roles_member(self):
        from plone.app.caching.operations.etags import Roles

        class DummyMember(object):

            def getRolesInContext(self, context):
                return ['Member', 'Manager']

        class DummyPortalState(object):
            implements(Interface)
            adapts(DummyContext, Interface)

            def __init__(self, context, request):
                pass

            def anonymous(self):
                return False

            def member(self):
                return DummyMember()

        provideAdapter(DummyPortalState, name=u"plone_portal_state")

        environ = {'SERVER_NAME': 'example.com', 'SERVER_PORT': '80'}
        response = HTTPResponse()
        request = HTTPRequest(StringIO(), environ, response)
        published = DummyPublished(DummyContext())

        etag = Roles(published, request)

        self.assertEqual('Manager;Member', etag())
Example #15
0
    def test_LastModified(self):
        from plone.app.caching.operations.etags import LastModified

        mod = datetime(2010, 1, 2, 3, 4, 5, 6, tzlocal())
        utcStamp = time.mktime(mod.utctimetuple())

        class DummyLastModified(object):
            implements(ILastModified)
            adapts(DummyPublished)

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

            def __call__(self):
                return mod

        provideAdapter(DummyLastModified)

        environ = {'SERVER_NAME': 'example.com', 'SERVER_PORT': '80'}
        response = HTTPResponse()
        request = HTTPRequest(StringIO(), environ, response)
        published = DummyPublished(DummyContext())

        etag = LastModified(published, request)
        self.assertEqual(str(utcStamp), etag())
Example #16
0
    def test_enabled(self):
        context = FauxContext()
        
        request = FauxRequest()
        alsoProvides(request, IAttributeAnnotatable)
        setRequest(request)

        configlet= CachePurgingConfiglet()
        provideUtility(configlet, ICachePurgingConfiglet)

        settings = getUtility(ICachePurgingConfiglet)
        settings.enabled = True
        settings.cachingProxies = ('http://localhost:1234',)
        
        class FauxPurgePaths(object):
            implements(IPurgePaths)
            adapts(FauxContext)
        
            def __init__(self, context):
                self.context = context
        
            def getRelativePaths(self):
                return ['/foo', '/bar']
        
            def getAbsolutePaths(self):
                return []
        
        provideAdapter(FauxPurgePaths, name="test1")
        
        notify(Purge(context))
        
        self.assertEquals({'zojax.cachepurging.urls': set(['/foo', '/bar'])},
                          dict(IAnnotations(request)))
Example #17
0
    def test_request_not_annotatable(self):
        context = FauxContext()
        
        request = FauxRequest()
        setRequest(request)

        configlet= CachePurgingConfiglet()
        provideUtility(configlet, ICachePurgingConfiglet)

        settings = getUtility(ICachePurgingConfiglet)
        settings.enabled = True
        settings.cachingProxies = ('http://localhost:1234',)
        
        class FauxPurgePaths(object):
            implements(IPurgePaths)
            adapts(FauxContext)
        
            def __init__(self, context):
                self.context = context
        
            def getRelativePaths(self):
                return ['/foo', '/bar']
        
            def getAbsolutePaths(self):
                return []
        
        provideAdapter(FauxPurgePaths, name="test1")
        
        try:
            notify(Purge(context))
        except:
            self.fail()
Example #18
0
    def test_criteria_adapter(self):
        setRoles(self.portal, TEST_USER_ID, ('Manager',))

        self.portal.invokeFactory('LibrarySearch', 'library', title=u"Library")
        library_obj = self.portal['library']

        provideAdapter(get_extra_criteria,
            adapts=[IExtendedLibrarySearch],
            provides=library.ISearchCriteriaProvider,
            name="more-criteria")

        alsoProvides(library_obj, IExtendedLibrarySearch)

        adapters = getAdapters((library_obj, ),
            provided=library.ISearchCriteriaProvider)

        criteria = {}
        for name, value in adapters:
            criteria.update(value)

        expected = {}
        expected.update(library.get_basic_criteria(library_obj))
        expected.update(get_extra_criteria(library_obj))

        self.maxDiff = None
        self.assertEqual(criteria, expected)
Example #19
0
    def test_baselineNoCopyReferences(self):
        # ensure that custom state is maintained with the no copy adapter

        # setup the named ref adapter
        from zope import component
        from Products.Archetypes.interfaces import IBaseObject
        from plone.app.iterate import relation, interfaces
        from plone.app.iterate.tests.utils import CustomReference

        component.provideAdapter(
            adapts=(IBaseObject,),
            provides=interfaces.ICheckinCheckoutReference,
            factory=relation.NoCopyReferenceAdapter,
            name="zebra")

        doc = self.portal.docs.doc1
        ref = doc.addReference(
            self.portal.docs, "zebra", referenceClass=CustomReference)
        ref.custom_state = "hello world"

        wc = ICheckinCheckoutPolicy(doc).checkout(self.portal.workarea)

        self.assertEqual(len(wc.getReferences("zebra")), 0)

        doc = ICheckinCheckoutPolicy(wc).checkin("updated")

        self.assertEqual(len(doc.getReferences("zebra")), 1)

        ref = doc.getReferenceImpl("zebra")[0]

        self.assert_(hasattr(ref, "custom_state"))
        self.assertEqual(ref.custom_state, "hello world")
Example #20
0
    def test_off_switch(self):

        class Transform1(FauxTransformBase):

            order = 0

            def transformBytes(self, result, encoding):
                return result + ' transformed'

            def transformUnicode(self, result, encoding):
                return result + u' transformed'

            def transformIterable(self, result, encoding):
                return ''.join(result) + ' transformed'

        provideAdapter(Transform1, name=u'test.one')

        published = FauxPublished()
        request = FauxRequest(published)
        request.environ['plone.transformchain.disable'] = True

        result = ['Blah']
        encoding = 'utf-8'

        new_result = self.t(request, result, encoding)
        self.assertEqual(None, new_result)
def registerPublisherForFTI(fti):
    # This registers a publisher that will allow to traverse to each sql item
    if not getattr(fti, 'sql_table', None):
        return
    name = getattr(fti, 'sql_folder_id', fti.getId())
    has_folder = False
    if name and IRelationValue.providedBy(name):
        obj = name.to_object
        if obj:
            has_folder = True
            name = obj.getId()
        else:
            name = fti.getId()
    elif not name:
        name = fti.getId()
    if not has_folder:
        view = queryMultiAdapter((None, ICollectiveBehaviorSQLLayer), IBrowserView, name='data-'+name, default=None)
        if view != None:
            return view
        publisher = SQLItemPublisher
        provideAdapter(
            factory=publisher,
            adapts=(None, ICollectiveBehaviorSQLLayer),
            provides=IBrowserView,
            name='data-'+name)

        LOG.info('Publisher registered for data-'+name)
Example #22
0
    def test_retry_keeps_everything(self):
        """lowlevel test for retry (see #98440)"""
        from zope.publisher.browser import TestRequest
        from zope.publisher.skinnable import setDefaultSkin
        from zope.publisher.interfaces import IDefaultSkin
        from zope.publisher.interfaces.browser import IBrowserRequest
        from zope.publisher.interfaces.browser import IBrowserSkinType
        # create a retryable request
        request = TestRequest()
        self.assertTrue(request.supportsRetry())
        # create a skin and register it as the default skin
        class ISomeSkin(Interface):
            pass
        alsoProvides(ISomeSkin, IBrowserSkinType)
        provideAdapter(ISomeSkin, (IBrowserRequest,), IDefaultSkin)
        # set the default skin for the request
        setDefaultSkin(request)

        # create a retried request
        retried = request.retry()

        # the requests are not the same
        self.assertTrue(request is not retried)
        # the requests both provide the default skin
        self.assertTrue(ISomeSkin.providedBy(request))
        self.assertTrue(ISomeSkin.providedBy(retried))
def registerPublisherForFTI(fti):
    # This registers a publisher that will allow to traverse to each sql item
    if not getattr(fti, 'sql_table', None):
        return
    name = getattr(fti, 'sql_folder_id', fti.id)
    has_folder = False
    if name and IRelationValue.providedBy(name):
        obj = name.to_object
        if obj:
            has_folder = True
            name = obj.getId()
        else:
            name = fti.context.getId()
    elif name and name.startswith('/'):
        portal = getToolByName(getSite(), "portal_url").getPortalObject()
        try:
            folder = portal.restrictedTraverse(name)
            has_folder = True
        except:
            pass
    elif not name:
        name = fti.context.getId()
    if not has_folder:
        view = queryMultiAdapter((None, ICollectiveBehaviorSQLLayer), IBrowserView, name='data-'+name, default=None)
        if view != None:
            return view
        publisher = SQLItemPublisher
        provideAdapter(
            factory=publisher,
            adapts=(None, ICollectiveBehaviorSQLLayer),
            provides=IBrowserView,
            name='data-'+name)

        LOG.info('Publisher registered for data-'+name)
Example #24
0
def pdfSetUp(test=None):
    setup.placefulSetUp()
    sbsetup.setUpCalendaring()
    app = ApplicationStub()
    provideAdapter(lambda x: app, (None,), ISchoolToolApplication)
    provideAdapter(getApplicationPreferences,
                   (ISchoolToolApplication,), IApplicationPreferences)
    def setUp(self):
        super(TestInvitationFormEmailing, self).setUp()
        self.login_as_portal_owner()
        provideAdapter(adapts=(Interface, IBrowserRequest),
                       provides=Interface,
                       factory=InviteForm,
                       name="invite")

        # create a workspace
        self.ws = api.content.create(
            self.portal,
            "ploneintranet.workspace.workspacefolder",
            "alejandro-workspace",
            title="Alejandro workspace")

        self.app = self.layer['app']
        self.portal = self.layer['portal']
        self.request = self.layer['request']
        # don't import this at the top, because it screws up the setup
        # and none of the tests can run
        from Products.CMFPlone.tests.utils import MockMailHost
    #    # Mock the mail host so we can test sending the email
        mockmailhost = MockMailHost('MailHost')

        if not hasattr(mockmailhost, 'smtp_host'):
            mockmailhost.smtp_host = 'localhost'

        self.portal.MailHost = mockmailhost
        sm = self.portal.getSiteManager()
        sm.registerUtility(component=mockmailhost, provided=IMailHost)

        self.mailhost = api.portal.get_tool('MailHost')

        self.portal._updateProperty('email_from_name', 'Portal Owner')
        self.portal._updateProperty('email_from_address', '*****@*****.**')
Example #26
0
    def test_off_switch(self):
        provideAdapter(DefaultRulesetLookup)
        provideUtility(Registry(), IRegistry)
        registry = getUtility(IRegistry)
        registry.registerInterface(ICacheSettings)
        settings = registry.forInterface(ICacheSettings)
        settings.enabled = False

        z3c.caching.registry.register(DummyView, 'testrule')
        settings.operationMapping = {'testrule': 'op1'}

        @implementer(ICachingOperation)
        @adapter(Interface, Interface)
        class DummyOperation(object):

            def __init__(self, published, request):
                self.published = published
                self.request = request

            def interceptResponse(self, rulename, response):
                return None

            def modifyResponse(self, rulename, response):
                response['X-Mutated'] = rulename

        provideAdapter(DummyOperation, name='op1')

        view = DummyView()
        request = DummyRequest(view, DummyResponse())

        MutatorTransform(view, request).transformUnicode(u'', 'utf-8')

        self.assertEqual({'PUBLISHED': view}, dict(request))
        self.assertEqual({}, dict(request.response))
Example #27
0
    def test_match_abort(self):
        provideAdapter(DefaultRulesetLookup)
        provideUtility(Registry(), IRegistry)
        registry = getUtility(IRegistry)
        registry.registerInterface(ICacheSettings)
        settings = registry.forInterface(ICacheSettings)
        settings.enabled = True

        z3c.caching.registry.register(DummyView, 'testrule')
        settings.operationMapping = {'testrule': 'op1'}

        @implementer(ICachingOperation)
        @adapter(Interface, Interface)
        class DummyOperation(object):

            def __init__(self, published, request):
                self.published = published
                self.request = request

            def modifyResponse(self, rulename, response):
                pass

            def interceptResponse(self, rulename, response):
                response.addHeader('X-Cache-Foo', 'test')
                return None

        provideAdapter(DummyOperation, name='op1')

        view = DummyView()
        request = DummyRequest(view, DummyResponse())

        intercept(DummyEvent(request))
        self.assertEqual({'PUBLISHED': view}, dict(request))
        self.assertEqual({'X-Cache-Rule': ['testrule'],
                          'X-Cache-Foo': ['test']}, dict(request.response))
Example #28
0
def _setUpDefaultTraversable():
    from zope.interface import Interface
    from zope.component import provideAdapter
    from zope.traversing.interfaces import ITraversable
    from zope.traversing.adapters import DefaultTraversable

    provideAdapter(DefaultTraversable, (Interface,), ITraversable)
Example #29
0
    def test_swallow_other_error(self):

        @implementer(IRulesetLookup)
        @adapter(Interface, Interface)
        class DummyRulesetLookup(object):

            def __init__(self, published, request):
                self.published = published
                self.request = request

            def __call__(self):
                raise AttributeError('Should be swallowed and logged')

        provideAdapter(DummyRulesetLookup)

        provideUtility(Registry(), IRegistry)
        registry = getUtility(IRegistry)
        registry.registerInterface(ICacheSettings)
        settings = registry.forInterface(ICacheSettings)
        settings.enabled = True
        settings.operationMapping = {'foo': 'bar'}

        view = DummyView()
        request = DummyRequest(view, DummyResponse())

        try:
            intercept(DummyEvent(request))
        except Exception:
            self.fail('Intercept should not raise')
Example #30
0
    def test_form_create(self):

        # Context and request
        context = Container(u"container")
        request = TestRequest()

        # FTI - returns dummy factory name

        fti_mock = DexterityFTI(u"testtype")
        fti_mock.factory = u'testfactory'
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        # The form we're testing
        form = DefaultAddForm(context, request)
        form.portal_type = u"testtype"

        class ISchema(Interface):
            foo = schema.TextLine()
        form.fields = Fields(ISchema)

        # createObject and applyChanges

        obj_dummy = Item(id="dummy")
        alsoProvides(obj_dummy, ISchema)
        data_dummy = {u"foo": u"bar"}

        from zope.component import createObject
        self.patch_global(createObject, return_value=obj_dummy)

        provideAdapter(AttributeField)

        self.assertEqual(obj_dummy, form.create(data_dummy))
        self.assertEqual("testtype", obj_dummy.portal_type)
Example #31
0
 def setUp(self):
     super(Test, self).setUp()
     provideAdapter(AbsoluteURL, (None, None), IAbsoluteURL)
Example #32
0

@provider(IFormFieldProvider)
class IProductExcludeFromNavigation(IExcludeFromNavigation):
    """Exclude from navigation behavior for products.

    Could not find a sane way of providing default values for general behavior
    attributes based on content interface which the behavior is bound to.
    Registering ComputedWidgetAttribute to context does not help because
    context is the container in case of add form instead of a content instance.
    """


provideAdapter(
    ComputedWidgetAttribute(
        lambda data: True, field=IProductExcludeFromNavigation["exclude_from_nav"]
    ),
    name="default",
)


@provider(IFormFieldProvider)
class IProductTilesViewSettingsBehavior(model.Schema):
    """Product tiles view settings behavior.

    This behavior is not applied to any content types by default. It can be
    used on folderish objects where product tiles view is enabled in order to
    configure product tiles view.
    """

    model.fieldset(
        "settings",
Example #33
0
 def setUp(self):
     self.portal = self.layer["portal"]
     self.request = self.layer["request"]
     alsoProvides(self.request, ICartExtensionLayer)
     provideAdapter(cartmocks.MockShipping)
     self.shipping = IShipping(self.portal)
Example #34
0
        else:
            lifetime.visible = False
            lifetime.connectable = False

    def disconnect(self, handle):
        super(MessageLifelineConnect, self).disconnect(handle)

        line = self.line
        send = self.get_connected(line.head)
        received = self.get_connected(line.tail)
        lifeline = self.element
        lifetime = lifeline.lifetime

        # if a message is delete message, then disconnection causes
        # lifeline to be no longer destroyed (note that there can be
        # only one delete message connected to lifeline)
        if received and line.subject.messageSort == 'deleteMessage':
            received.is_destroyed = False
            received.request_update()

        self.disconnect_lifelines(line)

        if len(list(self.canvas.get_connections(connected=lifeline))) == 1:
            # after disconnection count of connected items will be
            # zero, so allow connections to lifeline's lifetime
            lifetime.connectable = True
            lifetime.min_length = lifetime.MIN_LENGTH


component.provideAdapter(MessageLifelineConnect)
Example #35
0
    def test_local_roles_disregard_adapter(self):
        """Test that borg.localrole-adpaters are not copied when granting
        local roles."""

        portal = api.portal.get()
        folder = api.content.create(
            container=portal,
            type='Folder',
            id='folder_one',
            title='Folder One',
        )
        api.group.create(groupname='foo')

        self.assertEqual(
            api.group.get_roles(groupname='foo', obj=folder),
            ['Authenticated'],
        )
        self.assertEqual(
            api.group.get_roles(groupname='foo', obj=folder, inherit=False),
            [],
        )

        # throw in a adapter granting the reviewer-roles
        @adapter(Interface)
        @implementer(ILocalRoleProvider)
        class LocalRoleProvider(object):
            def __init__(self, context):
                self.context = context

            def getRoles(self, principal_id):
                return ('Reviewer', )

        provideAdapter(LocalRoleProvider)

        # the adapter-role is added for get_role
        self.assertItemsEqual(
            api.group.get_roles(groupname='foo', obj=folder),
            ['Authenticated', 'Reviewer'],
        )

        self.assertItemsEqual(
            api.group.get_roles(groupname='foo', obj=folder, inherit=False),
            ['Reviewer'],
        )

        # Assign a local role
        api.group.grant_roles(
            groupname='foo',
            roles=['Contributor'],
            obj=folder,
        )
        self.assertItemsEqual(
            api.group.get_roles(groupname='foo', obj=folder),
            ['Authenticated', 'Contributor', 'Reviewer'],
        )

        # The adapter role in in the local roles but not persistent
        self.assertItemsEqual(
            api.group.get_roles(groupname='foo', obj=folder, inherit=False),
            ['Contributor', 'Reviewer'],
        )
        local_roles = getattr(folder, '__ac_local_roles__', {})
        self.assertItemsEqual(
            local_roles.get('foo'),
            ['Contributor'],
        )
        # cleanup
        gsm = getGlobalSiteManager()
        gsm.unregisterAdapter(
            factory=LocalRoleProvider,
            provided=ILocalRoleProvider,
        )
Example #36
0
 def to_locatable_container(domain_class, *domain_containers):
     provideAdapter(location.ContainerLocation(*domain_containers),
                    (implementedBy(domain_class), ILocation))
    def test_add_comment(self):
        """Post a comment as logged-in user.
        """

        # Allow discussion
        self.portal.doc1.allow_discussion = True
        self.viewlet = CommentsViewlet(self.context, self.request, None, None)

        def make_request(form={}):
            request = TestRequest()
            request.form.update(form)
            alsoProvides(request, IFormLayer)
            alsoProvides(request, IAttributeAnnotatable)
            return request

        provideAdapter(
            adapts=(Interface, IBrowserRequest),
            provides=Interface,
            factory=CommentForm,
            name=u'comment-form',
        )

        # The form should return an error if the comment text field is empty
        request = make_request(form={})

        commentForm = getMultiAdapter(
            (self.context, request),
            name=u'comment-form',
        )
        commentForm.update()
        data, errors = commentForm.extractData()  # pylint: disable-msg=W0612

        self.assertEqual(len(errors), 1)
        self.assertFalse(commentForm.handleComment(commentForm, 'foo'))

        # The form is submitted successfully, if the required text field is
        # filled out
        request = make_request(form={'form.widgets.text': u'bar'})

        commentForm = getMultiAdapter(
            (self.context, request),
            name=u'comment-form',
        )
        commentForm.update()
        data, errors = commentForm.extractData()  # pylint: disable-msg=W0612

        self.assertEqual(len(errors), 0)
        self.assertFalse(commentForm.handleComment(commentForm, 'foo'))

        comments = IConversation(commentForm.context).getComments()
        comments = [comment for comment in comments]  # consume iterator
        self.assertEqual(len(comments), 1)

        for comment in comments:
            self.assertEqual(comment.text, u'bar')
            self.assertEqual(comment.creator, 'test_user_1_')
            self.assertEqual(comment.getOwner().getUserName(), 'test-user')
            local_roles = comment.get_local_roles()
            self.assertEqual(len(local_roles), 1)
            userid, roles = local_roles[0]
            self.assertEqual(userid, 'test_user_1_')
            self.assertEqual(len(roles), 1)
            self.assertEqual(roles[0], 'Owner')
Example #38
0
    enable_refresh = schema.Bool(
        title=_(u'Enable refresh'),
        description=_(u'Enable refresh of the current page.'),
        default=False,
    )

    ttl = schema.Int(
        title=_(u'Time to live'),
        description=_(u'Number of seconds after which to reload the current page.',),
        default=300,
    )

alsoProvides(IRefresh, IFormFieldProvider)


class TimeToLiveValidator(validator.SimpleFieldValidator):

    """z3c.form validator class for time to live"""

    def validate(self, value):
        """Validate the value on time to live input"""
        if value <= 0:
            raise Invalid(_(u'Value must be greater than zero.'))

# set conditions for which fields the validator class applies
validator.WidgetValidatorDiscriminators(TimeToLiveValidator, field=IRefresh['ttl'])

# register the validator so it will be looked up by z3c.form machinery
provideAdapter(TimeToLiveValidator)
Example #39
0
        page = super(PartitionPropertyPage, self).construct()

        if item.subject:
            if not item._toplevel:
                hbox = gtk.HBox(spacing=12)
                button = gtk.CheckButton(_('External'))
                button.set_active(item.subject.isExternal)
                button.connect('toggled', self._on_external_change)
                hbox.pack_start(button)
                page.pack_start(hbox, expand=False)
            else:
                pass
                #hbox = gtk.HBox(spacing=12)
                #button = gtk.CheckButton(_('Dimension'))
                #button.set_active(item.subject.isDimension)
                #button.connect('toggled', self._on_dimension_change)

        return page

    @transactional
    def _on_external_change(self, button):
        item = self.item
        if item.subject:
            item.subject.isExternal = button.get_active()
        item.request_update()


component.provideAdapter(PartitionPropertyPage, name='Properties')

# vim:sw=4:et:ai
Example #40
0
            page.pack_start(hbox, expand=False)

        # stereotype attributes
        self.model = StereotypeAttributes(self.item.subject)
        tree_view = create_stereotype_tree_view(self.model)
        page.pack_start(tree_view)

        page.show_all()
        return page

    #@transactional
    #def _on_stereotype_selected(self, button, stereotype):
    #    subject = self.item.subject
    #    if button.get_active():
    #        modelfactory.apply_stereotype(self.element_factory, subject, stereotype)
    #    else:
    #        modelfactory.remove_stereotype(subject, stereotype)
    #    self.model.refresh()

    @transactional
    def _on_show_stereotypes_attrs_change(self, button):
        self.item.show_stereotypes_attrs = button.get_active()
        self.item.request_update()


component.provideAdapter(StereotypePage,
                         adapts=[uml2.Element],
                         name='Stereotypes')

# vim:sw=4:et:ai
Example #41
0
 def _viewlet_manager(factory):
     component.provideAdapter(factory, 
         adapts=(for_, layer, view),
         provides=provides,
         name=name)
     return factory
Example #42
0
 def setUp(self):
     SCHEMA_CACHE.clear()
     provideAdapter(DefaultOrdering)
     provideAdapter(AttributeAnnotations)
Example #43
0
 def setUp(self):
     provideAdapter(instanceSchemaFactory)
Example #44
0
 def setUp(self):
     provideAdapter(AttributeAnnotations)
     provideAdapter(persistentFieldAdapter)
     provideHandler(queuePurge)
Example #45
0
def defineDefaultViewName(name, for_=None):
    provideAdapter(name, (for_, IBrowserRequest), IDefaultViewName, '')
Example #46
0
 def _adapter(factory):
     component.provideAdapter(factory, adapts, provides, name)
     return factory
Example #47
0
 def setUp(self):
     from zope.component import provideAdapter
     from zope.traversing.adapters import DefaultTraversable
     PlacelessSetup.setUp(self)
     provideAdapter(DefaultTraversable, (None, ))
Example #48
0
    def _setUpAdapters(self):
        from zope.component import provideAdapter
        #from OFS.Image import File

        from Products.GenericSetup.interfaces import IFilesystemExporter
        from Products.GenericSetup.interfaces import IFilesystemImporter
        from Products.GenericSetup.interfaces import ICSVAware
        from Products.GenericSetup.interfaces import IINIAware
        from Products.CMFCore.interfaces import IFolderish

        from Products.CMFCore.exportimport.content import \
             StructureFolderWalkingAdapter
        from Products.GenericSetup.content import \
             CSVAwareFileAdapter
        from Products.GenericSetup.content import \
             INIAwareFileAdapter

        #from Products.CMFCore.exportimport.content import \
        #        OFSFileAdapter

        provideAdapter(StructureFolderWalkingAdapter, (IFolderish, ),
                       IFilesystemExporter)

        provideAdapter(StructureFolderWalkingAdapter, (IFolderish, ),
                       IFilesystemImporter)

        provideAdapter(CSVAwareFileAdapter, (ICSVAware, ), IFilesystemExporter)

        provideAdapter(CSVAwareFileAdapter, (ICSVAware, ), IFilesystemImporter)

        provideAdapter(INIAwareFileAdapter, (IINIAware, ), IFilesystemExporter)

        provideAdapter(INIAwareFileAdapter, (IINIAware, ), IFilesystemImporter)
        def _setUpAdapters(self):
            from zope.component import provideAdapter
            from OFS.interfaces import IObjectManager
            from OFS.interfaces import IPropertyManager

            from Products.GenericSetup.interfaces import IContentFactoryName
            from Products.GenericSetup.interfaces import ICSVAware
            from Products.GenericSetup.interfaces import IDAVAware
            from Products.GenericSetup.interfaces import IFilesystemExporter
            from Products.GenericSetup.interfaces import IINIAware
            from Products.GenericSetup.content import \
                FolderishExporterImporter
            from Products.GenericSetup.content import \
                SimpleINIAware
            from Products.GenericSetup.content import \
                CSVAwareFileAdapter
            from Products.GenericSetup.content import \
                INIAwareFileAdapter
            from Products.GenericSetup.content import \
                DAVAwareFileAdapter

            from Products.PluginRegistry.interfaces import IPluginRegistry
            from Products.PluginRegistry.exportimport \
                import PluginRegistryFileExportImportAdapter

            from Products.PluggableAuthService.exportimport \
                import PAS_CF_Namer

            provideAdapter(FolderishExporterImporter, (IObjectManager, ),
                           IFilesystemExporter)

            provideAdapter(SimpleINIAware, (IPropertyManager, ), IINIAware)

            provideAdapter(CSVAwareFileAdapter, (ICSVAware, ),
                           IFilesystemExporter)

            provideAdapter(INIAwareFileAdapter, (IINIAware, ),
                           IFilesystemExporter)

            provideAdapter(DAVAwareFileAdapter, (IDAVAware, ),
                           IFilesystemExporter)

            provideAdapter(PluginRegistryFileExportImportAdapter,
                           (IPluginRegistry, ), IFilesystemExporter)

            provideAdapter(PAS_CF_Namer, (IPluginRegistry, ),
                           IContentFactoryName)
Example #50
0
            noLongerProvides(self.field, ILanguageIndependentField)

    languageindependent = property(
        _read_languageindependent, _write_languageindependent)


# IFieldLanguageIndependent could be registered directly as a named adapter
# providing IFieldEditorExtender for ISchemaContext and IField. But we can
# also register a separate callable which returns the schema only if
# additional conditions pass:
@adapter(ISchemaContext, IField)
def get_li_schema(schema_context, field):
    behavior = 'plone.app.multilingual.dx.interfaces.IDexterityTranslatable'
    fti = getattr(schema_context, 'fti', None)
    if fti and behavior in getattr(fti, 'behaviors', []):
        return IFieldLanguageIndependent


# Register the callable which makes the field edit form know about the
# new schema:
provideAdapter(
    get_li_schema,
    provides=IFieldEditorExtender,
    name='plone.schemaeditor.languageindependent')


# And the adapter for getting/setting the value.
provideAdapter(
    FieldLanguageIndependentAdapter,
    provides=IFieldLanguageIndependent)
Example #51
0
 def setUp(self):
     obj = Item('obj')
     self.helpers = self._makeOne(obj, DummySetupEnviron())
     provideAdapter(MarkerInterfacesAdapter, (IItem, ))
     provideInterface('', IDummyMarker)
Example #52
0
def provideRecorder( klass, change_table ):
    domain_interface = queryModelInterface( klass )
    recorder = type( "%sChangeRecorder"%(klass.__name__),
                     (ChangeRecorder,),
                     {'change_table':change_table} )
    component.provideAdapter( recorder, (domain_interface,), (interfaces.IRecorder,))
Example #53
0
    colorize_project_rows = schema.Bool(
        title=_(u"colorize project's rows"),
        description=_(u"Visual way to highlight internal panes in dashboards"),
        default=False,
    )

    @invariant
    def validateSettings(data):
        mandatory_check(data, field_constraints)
        position_check(data, field_constraints)


validator.WidgetValidatorDiscriminators(
    RemovedValueIsNotUsedByCategoriesFieldValidator,
    field=IProjectSpace['categories_values'])
provideAdapter(RemovedValueIsNotUsedByCategoriesFieldValidator)

validator.WidgetValidatorDiscriminators(
    RemovedValueIsNotUsedByPriorityFieldValidator,
    field=IProjectSpace['priority_values'])
provideAdapter(RemovedValueIsNotUsedByPriorityFieldValidator)

validator.WidgetValidatorDiscriminators(
    RemovedValueIsNotUsedByBudgetTypesFieldValidator,
    field=IProjectSpace['budget_types'])
provideAdapter(RemovedValueIsNotUsedByBudgetTypesFieldValidator)


class ProjectSpace(Container):
    """ """
    implements(IProjectSpace)
Example #54
0
def setUp(test):
    test.globs['this_directory'] = os.path.dirname(__file__)
    testing.setUp(test)
    provideAdapter(process.PythonExpressionEvaluator)
Example #55
0
        if hct and oct:
            logger.debug('Disconnecting %s and %s' % (hct, oct))
            try:
                if hct.subject and isinstance(oct.subject, uml2.Comment):
                    del oct.subject.annotatedElement[hct.subject]
                elif hct.subject and oct.subject:
                    del hct.subject.annotatedElement[oct.subject]
            except ValueError:
                logger.debug(
                    'Invoked CommentLineElementConnect.disconnect() for nonexistant relationship'
                )

        super(CommentLineElementConnect, self).disconnect(handle)


component.provideAdapter(CommentLineElementConnect)


class CommentLineLineConnect(AbstractConnect):
    """
    Connect a comment line to any diagram line.
    """
    component.adapts(items.DiagramLine, items.CommentLineItem)

    def allow(self, handle, port):
        """
        In addition to the normal check, both line ends may not be connected
        to the same element. Same goes for subjects.
        One of the ends should be connected to a uml2.Comment element.
        """
        opposite = self.line.opposite(handle)
Example #56
0
def setUp(test=None):
    testing.setUp()
    eventtesting.setUp()

    provideAdapter(persistentFieldAdapter)
    provideAdapter(choicePersistentFieldAdapter)
Example #57
0
 def setUp(self):
     super(TestResource, self).setUp()
     component.provideAdapter(AbsoluteURL, (None, None), IAbsoluteURL)
Example #58
0
    def create(self):
        from zope.component import provideUtility

        from collective.zamqp.interfaces import IBrokerConnection
        from collective.zamqp.connection import BrokerConnection

        connection = BrokerConnection(connection_id=self.connection_id,
                                      hostname=self.hostname,
                                      port=self.port,
                                      virtual_host=self.virtual_host,
                                      username=self.username,
                                      password=self.password,
                                      heartbeat=self.heartbeat,
                                      prefetch_count=self.prefetch_count,
                                      tx_select=self.tx_select)

        # set expected ZServer-properties to support debugtoolbar
        connection.server_name = "ZAMQP Broker Connection"
        connection.ip = None

        provideUtility(connection, IBrokerConnection, name=self.connection_id)

        if self.keepalive:
            from collective.zamqp.utils import logger
            logger.default(u"Setting up keepalive (%s s) for connection '%s'",
                           self.keepalive, self.connection_id)

            # register a ping producer, a ping consumer, a ping view and a ping
            # clock-server to keep the connection alive

            from collective.zamqp.interfaces import IProducer, IConsumer
            from collective.zamqp import keepalive

            name = "%s.ping" % self.connection_id

            # the producer
            producer = keepalive.PingProducer(self.connection_id)
            provideUtility(producer, IProducer, name=name)

            # the consumer
            consumer = keepalive.PingConsumer(self.connection_id)
            provideUtility(consumer, IConsumer, name=name)

            from zope.interface import Interface
            from zope.component import provideAdapter

            from OFS.interfaces import IApplication

            # the view
            ping = lambda context, request: lambda: keepalive.ping(name)
            provideAdapter(ping,
                           adapts=(IApplication, Interface),
                           provides=Interface,
                           name=name)

            # the clock-server
            from ZServer.AccessLogger import access_logger
            from ZServer.ClockServer import ClockServer
            clock = ClockServer(method="/%s" % name,
                                period=self.keepalive,
                                host="localhost",
                                logger=access_logger)

            # just in case, store the created utilities, view and server
            connection._keepalive = {
                "producer": producer,
                "consumer": consumer,
                "view": ping,
                "clock": clock
            }

        if self.producer:
            # generate default producer with the name of the connection
            from collective.zamqp.interfaces import IProducer
            from collective.zamqp.producer import Producer

            producer = Producer(self.connection_id,
                                exchange="",
                                routing_key="",
                                durable=False,
                                auto_declare=False)
            provideUtility(producer, IProducer, name=self.connection_id)

        # set expected ZServer-properties to support debugtoolbar
        connection.server_name = "ZAMQP Broker Connection"
        connection.ip = None

        return connection
Example #59
0
    def setUp(self):
        provideAdapter(QueryParser)
        provideAdapter(QueryNullParser)
        provideAdapter(QueryOptimizer)
        provideAdapter(Rewriter)
        provideAdapter(AlgebraOptimizer)
        provideAdapter(AlgebraCompiler)
        provideAdapter(Metadata)
        registerAdapters()
        setupInterfaces(self)
        setupCatalog(self)

        self.engine = OCQLEngine()
Example #60
0
    def test_grant_roles_disregards_adapter(self):
        """Test that borg.localrole-adpaters are not copied when granting
        local roles."""
        if six.PY2:
            assertCountEqual = self.assertItemsEqual
        else:
            assertCountEqual = self.assertCountEqual

        portal = api.portal.get()
        folder = api.content.create(
            container=portal,
            type='Folder',
            id='folder_one',
            title='Folder One',
        )
        document = api.content.create(
            container=folder,
            type='Document',
            id='document_one',
            title='Document One',
        )
        user = api.user.create(
            username='******',
            email='*****@*****.**',
            password='******',
        )

        assertCountEqual(
            api.user.get_roles(username='******', obj=folder),
            ['Member', 'Authenticated'],
        )
        self.assertFalse(
            api.user.get_roles(user=user, obj=folder, inherit=False), )

        # throw in a adapter granting the reviewer-roles
        @adapter(Interface)
        @implementer(ILocalRoleProvider)
        class LocalRoleProvider(object):
            def __init__(self, context):
                self.context = context

            def getRoles(self, principal_id):
                return ('Reviewer', )

        provideAdapter(LocalRoleProvider)

        # the adapter-role is added for get_role
        assertCountEqual(
            api.user.get_roles(username='******', obj=folder),
            ['Member', 'Authenticated', 'Reviewer'],
        )

        assertCountEqual(
            api.user.get_roles(username='******', obj=folder, inherit=False),
            ['Reviewer'],
        )

        # Assign a local role
        api.user.grant_roles(
            username='******',
            roles=['Contributor'],
            obj=folder,
        )
        assertCountEqual(
            api.user.get_roles(username='******', obj=folder),
            ['Member', 'Authenticated', 'Contributor', 'Reviewer'],
        )

        # The adapter role is in in the local roles but not persistent
        assertCountEqual(
            api.user.get_roles(username='******', obj=folder, inherit=False),
            ['Contributor', 'Reviewer'],
        )
        local_roles = getattr(folder, '__ac_local_roles__', {})
        self.assertEqual(
            local_roles.get('chuck'),
            ['Contributor'],
        )

        assertCountEqual(
            api.user.get_roles(username='******', obj=document, inherit=False),
            ['Reviewer'],
        )
        assertCountEqual(
            api.user.get_roles(username='******', obj=document),
            ['Member', 'Authenticated', 'Contributor', 'Reviewer'],
        )

        # add a group and test mix of group and adapter and user-roles
        api.group.create('foo')
        api.group.grant_roles(
            groupname='foo',
            roles=['Contributor'],
            obj=document,
        )
        api.group.add_user(groupname='foo', username='******')

        assertCountEqual(
            api.user.get_roles(username='******', obj=document, inherit=False),
            ['Contributor', 'Reviewer'],
        )
        api.group.grant_roles(groupname='foo', roles=['Manager'], obj=folder)
        assertCountEqual(
            api.user.get_roles(username='******', obj=document, inherit=False),
            ['Contributor', 'Reviewer'],
        )
        assertCountEqual(
            api.user.get_roles(username='******', obj=document),
            [
                'Contributor',
                'Reviewer',
                'Manager',
                'Authenticated',
                'Member',
            ],
        )
        assertCountEqual(
            api.user.get_roles(username='******', obj=folder),
            [
                'Contributor',
                'Reviewer',
                'Manager',
                'Authenticated',
                'Member',
            ],
        )
        assertCountEqual(
            api.user.get_roles(username='******', obj=folder, inherit=False),
            ['Contributor', 'Reviewer', 'Manager'],
        )

        # cleanup
        gsm = getGlobalSiteManager()
        gsm.unregisterAdapter(
            factory=LocalRoleProvider,
            provided=ILocalRoleProvider,
        )