def test_getattr_consults_schema_item_default_factory_with_context(self):

        content = Item()
        content.id = u"id"
        content.portal_type = u"testtype"

        from zope.interface import provider
        from zope.schema.interfaces import IContextAwareDefaultFactory

        @provider(IContextAwareDefaultFactory)
        def defaultFactory(context):
            return u"{0:s}_{1:s}".format(context.id, context.portal_type)

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo",
                                       defaultFactory=defaultFactory)
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        self.assertEqual(u"id_testtype", content.foo)
        self.assertEqual(None, content.bar)
        self.assertEqual(u"id", content.id)
        self.assertRaises(AttributeError, getattr, content, 'baz')
    def test_repeated_behavior_registration_lookup(self):

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        # Mock a test behavior
        class ITestBehavior(Interface):
            pass
        self.expect(fti_mock.behaviors).result([ITestBehavior.__identifier__])
        from plone.behavior.registration import BehaviorRegistration
        registration = BehaviorRegistration(
            title=u"Test Behavior",
            description=u"Provides test behavior",
            interface=Interface,
            marker=ITestBehavior,
            factory=None
        )
        from plone.behavior.interfaces import IBehavior
        self.mock_utility(
            registration,
            IBehavior,
            ITestBehavior.__identifier__
        )

        self.replay()

        r1 = SCHEMA_CACHE.behavior_registrations(u'testtype')
        r2 = SCHEMA_CACHE.behavior_registrations(u'testtype')

        self.assertTrue(r1[0] is r2[0] is registration)
Exemple #3
0
    def __getattr__(self, name):
        # python basics:  __getattr__ is only invoked if the attribute wasn't
        # found by __getattribute__
        #
        # optimization: sometimes we're asked for special attributes
        # such as __conform__ that we can disregard (because we
        # wouldn't be in here if the class had such an attribute
        # defined).
        if name.startswith('__'):
            raise AttributeError(name)

        # attribute was not found; try to look it up in the schema and return
        # a default
        value = _default_from_schema(
            self,
            SCHEMA_CACHE.get(self.portal_type),
            name
        )
        if value is not _marker:
            return value

        # do the same for each subtype
        for schema in SCHEMA_CACHE.subtypes(self.portal_type):
            value = _default_from_schema(self, schema, name)
            if value is not _marker:
                return value

        raise AttributeError(name)
Exemple #4
0
    def test_getattr_on_container_returns_children(self):

        content = Container()
        content.id = u"id"
        content.portal_type = u"testtype"

        content['foo'] = Item('foo')
        content['quux'] = Item('quux')

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo", default=u"foo_default")
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        # Schema field masks contained item
        self.assertEqual(u"foo_default", content.foo)

        # But we can still obtain an item
        self.assertTrue(isinstance(content['foo'], Item))
        self.assertEqual('foo', content['foo'].id)

        # And if the item isn't masked by an attribute, we can still getattr it
        self.assertTrue(isinstance(content['quux'], Item))
        self.assertEqual('quux', content['quux'].id)

        self.assertTrue(isinstance(getattr(content, 'quux'), Item))
        self.assertEqual('quux', getattr(content, 'quux').id)
    def test_getattr_on_container_returns_children(self):

        content = Container()
        content.id = u"id"
        content.portal_type = u"testtype"

        content['foo'] = Item('foo')
        content['quux'] = Item('quux')

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo", default=u"foo_default")
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        # Schema field masks contained item
        self.assertEqual(u"foo_default", content.foo)

        # But we can still obtain an item
        self.assertTrue(isinstance(content['foo'], Item))
        self.assertEqual('foo', content['foo'].id)

        # And if the item isn't masked by an attribute, we can still getattr it
        self.assertTrue(isinstance(content['quux'], Item))
        self.assertEqual('quux', content['quux'].id)

        self.assertTrue(isinstance(getattr(content, 'quux'), Item))
        self.assertEqual('quux', getattr(content, 'quux').id)
Exemple #6
0
    def test_no_tagged_value(self):

        # Mock schema model
        class ITestSchema(Interface):
            test = zope.schema.TextLine(title=u"Test")

        # Mock FTI
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ITestSchema)
        self.expect(fti_mock.behaviors).result(tuple())
        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        self.mocker.replay()

        SCHEMA_CACHE.clear()

        # Everything allowed
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('test', u"foo"))
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('foo', u"bar"))

        # Unknown attributes are allowed
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__(
                'random', u"stuff"))
    def test_repeated_behavior_registration_lookup(self):

        fti = DexterityFTI(u"testtype")
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        # Mock a test behavior
        class ITestBehavior(Interface):
            pass
        fti.behaviors = [ITestBehavior.__identifier__]
        from plone.behavior.registration import BehaviorRegistration
        registration = BehaviorRegistration(
            title=u"Test Behavior",
            description=u"Provides test behavior",
            interface=Interface,
            marker=ITestBehavior,
            factory=None
        )
        from plone.behavior.interfaces import IBehavior
        self.mock_utility(
            registration,
            IBehavior,
            ITestBehavior.__identifier__
        )

        r1 = SCHEMA_CACHE.behavior_registrations(u'testtype')
        r2 = SCHEMA_CACHE.behavior_registrations(u'testtype')

        self.assertTrue(r1[0] is r2[0] is registration)
Exemple #8
0
 def setUp(self):
     self.portal = self.layer['portal']
     self.browser = Browser(self.layer['app'])
     setRoles(self.portal, TEST_USER_ID, ['Manager'])
     # Invalidate schema cache
     SCHEMA_CACHE.invalidate('Audio')
     SCHEMA_CACHE.invalidate('OGG Audio File')
    def test_repeated_behavior_registration_lookup(self):

        fti = DexterityFTI(u"testtype")
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        # Mock a test behavior
        class ITestBehavior(Interface):
            pass
        fti.behaviors = [ITestBehavior.__identifier__]
        from plone.behavior.registration import BehaviorRegistration
        registration = BehaviorRegistration(
            title=u"Test Behavior",
            description=u"Provides test behavior",
            interface=Interface,
            marker=ITestBehavior,
            factory=None
        )
        from plone.behavior.interfaces import IBehavior
        self.mock_utility(
            registration,
            IBehavior,
            ITestBehavior.__identifier__
        )

        r1 = SCHEMA_CACHE.behavior_registrations(u'testtype')
        r2 = SCHEMA_CACHE.behavior_registrations(u'testtype')

        self.assertTrue(r1[0] is r2[0] is registration)
    def test_no_tagged_value(self):

        # Mock schema model
        class ITestSchema(Interface):
            test = zope.schema.TextLine(title=u"Test")

        # Mock FTI
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ITestSchema)
        self.expect(fti_mock.behaviors).result(tuple())
        self.mock_utility(fti_mock, IDexterityFTI, u"testtype")

        # Content item
        item = Item("test")
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        self.mocker.replay()

        SCHEMA_CACHE.clear()

        # Everything allowed
        self.assertTrue(item.__allow_access_to_unprotected_subobjects__("test", u"foo"))
        self.assertTrue(item.__allow_access_to_unprotected_subobjects__("foo", u"bar"))

        # Unknown attributes are allowed
        self.assertTrue(item.__allow_access_to_unprotected_subobjects__("random", u"stuff"))
Exemple #11
0
    def test_schema_exception(self):

        # Mock FTI
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))

        self.expect(fti_mock.lookupSchema()).throw(AttributeError)
        self.expect(fti_mock.behaviors).result(tuple())

        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        self.mocker.replay()

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('test', u"foo"))
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('foo', u"bar"))
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__(
                'random', u"stuff"))
Exemple #12
0
    def test_repeated_behavior_registration_lookup(self):

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        # Mock a test behavior
        class ITestBehavior(Interface):
            pass

        self.expect(fti_mock.behaviors).result([ITestBehavior.__identifier__])
        from plone.behavior.registration import BehaviorRegistration
        registration = BehaviorRegistration(
            title=u"Test Behavior",
            description=u"Provides test behavior",
            interface=Interface,
            marker=ITestBehavior,
            factory=None)
        from plone.behavior.interfaces import IBehavior
        self.mock_utility(registration, IBehavior,
                          ITestBehavior.__identifier__)

        self.replay()

        r1 = SCHEMA_CACHE.behavior_registrations(u'testtype')
        r2 = SCHEMA_CACHE.behavior_registrations(u'testtype')

        self.assertTrue(r1[0] is r2[0] is registration)
    def test_repeated_subtypes_lookup(self):

        fti = DexterityFTI(u"testtype")
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        # Mock a test behavior
        class ITestSchema(Interface):
            pass

        class ITestMarker(Interface):
            pass
        fti.behaviors = [ITestSchema.__identifier__]
        from plone.behavior.registration import BehaviorRegistration
        registration = BehaviorRegistration(
            title=u"Test Behavior",
            description=u"Provides test behavior",
            interface=ITestSchema,
            marker=ITestMarker,
            factory=None
        )
        from plone.behavior.interfaces import IBehavior
        self.mock_utility(
            registration,
            IBehavior,
            ITestSchema.__identifier__
        )

        s1 = SCHEMA_CACHE.subtypes(u"testtype")
        s2 = SCHEMA_CACHE.subtypes(u"testtype")

        self.assertTrue(s1[0] is s2[0] is ITestMarker)
Exemple #14
0
    def test_getattr_consults_schema_item_default_factory_with_context(self):

        content = Item()
        content.id = u"id"
        content.portal_type = u"testtype"

        from zope.interface import provider
        from zope.schema.interfaces import IContextAwareDefaultFactory

        @provider(IContextAwareDefaultFactory)
        def defaultFactory(context):
            return u"{0:s}_{1:s}".format(context.id, context.portal_type)

        class ISchema(Interface):
            foo = zope.schema.TextLine(title=u"foo",
                                       defaultFactory=defaultFactory)
            bar = zope.schema.TextLine(title=u"bar")

        # FTI mock
        fti_mock = Mock(wraps=DexterityFTI(u"testtype"))
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        SCHEMA_CACHE.invalidate('testtype')

        self.assertEqual(u"id_testtype", content.foo)
        self.assertEqual(None, content.bar)
        self.assertEqual(u"id", content.id)
        self.assertRaises(AttributeError, getattr, content, 'baz')
Exemple #15
0
    def test_schema_exception(self):

        # Mock FTI
        fti_mock = DexterityFTI(u"testtype")
        fti_mock.lookupSchema = Mock(side_effect=AttributeError)
        fti_mock.behaviors = ()

        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('test', u"foo")
        )
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('foo', u"bar")
        )
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('random', u"stuff")
        )
Exemple #16
0
    def test_no_tagged_value(self):

        # Mock schema model
        class ITestSchema(Interface):
            test = zope.schema.TextLine(title=u"Test")

        # Mock FTI
        fti_mock = DexterityFTI(u"testtype")
        fti_mock.lookupSchema = Mock(return_value=ITestSchema)
        fti_mock.behaviors = ()
        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        SCHEMA_CACHE.clear()

        # Everything allowed
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('test', u"foo")
        )
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('foo', u"bar")
        )

        # Unknown attributes are allowed
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('random', u"stuff")
        )
    def test_repeated_subtypes_lookup(self):

        fti = DexterityFTI(u"testtype")
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        # Mock a test behavior
        class ITestSchema(Interface):
            pass

        class ITestMarker(Interface):
            pass
        fti.behaviors = [ITestSchema.__identifier__]
        from plone.behavior.registration import BehaviorRegistration
        registration = BehaviorRegistration(
            title=u"Test Behavior",
            description=u"Provides test behavior",
            interface=ITestSchema,
            marker=ITestMarker,
            factory=None
        )
        from plone.behavior.interfaces import IBehavior
        self.mock_utility(
            registration,
            IBehavior,
            ITestSchema.__identifier__
        )

        s1 = SCHEMA_CACHE.subtypes(u"testtype")
        s2 = SCHEMA_CACHE.subtypes(u"testtype")

        self.assertTrue(s1[0] is s2[0] is ITestMarker)
 def setUp(self):
     self.portal = self.layer['portal']
     setRoles(self.portal, TEST_USER_ID, ['Manager'])
     self.portal.invokeFactory('Folder', 'test-folder')
     # Invalidate schema cache
     SCHEMA_CACHE.invalidate('Person')
     setRoles(self.portal, TEST_USER_ID, ['Member'])
     self.folder = self.portal['test-folder']
     self.setup_content(self.folder)
Exemple #19
0
def inactivate_filing_number(portal):
    unregister_layer('opengever.dossier.filing')

    portal_types = getToolByName(portal, 'portal_types')
    fti = portal_types.get('opengever.dossier.businesscasedossier')
    fti.behaviors = [behavior for behavior in fti.behaviors
                     if not behavior.endswith('IFilingNumber')]

    SCHEMA_CACHE.invalidate('opengever.dossier.businesscasedossier')
Exemple #20
0
def inactivate_filing_number(portal):
    unregister_layer('opengever.dossier.filing')

    portal_types = getToolByName(portal, 'portal_types')
    fti = portal_types.get('opengever.dossier.businesscasedossier')
    fti.behaviors = [behavior for behavior in fti.behaviors
                     if not behavior.endswith('IFilingNumber')]

    SCHEMA_CACHE.invalidate('opengever.dossier.businesscasedossier')
    def test_invalidate_cache(self):
        portal_type = u"testtype"
        fti = DexterityFTI(portal_type)
        SCHEMA_CACHE.get(portal_type)
        SCHEMA_CACHE.behavior_schema_interfaces(fti)
        self.assertIn("_v_schema_behavior_schema_interfaces", fti.__dict__.keys())

        invalidate_cache(fti)
        self.assertNotIn("_v_schema_behavior_schema_interfaces", fti.__dict__.keys())
Exemple #22
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)

        # Find the data we need to know if our cache needs to be invalidated
        direct_spec = getattr(inst, '__provides__', None)
        portal_type = getattr(inst, 'portal_type', None)

        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        fti = queryUtility(IDexterityFTI, name=portal_type)
        if fti is None:
            return spec

        schema = SCHEMA_CACHE.get(portal_type)
        subtypes = SCHEMA_CACHE.subtypes(portal_type)

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)
        updated = inst._p_mtime, schema, subtypes, direct_spec

        # See if we have a valid cache. Reasons to do this include:
        #
        #  - The schema was modified.
        #  - The subtypes were modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        if cache is not None:
            cached_mtime, cached_schema, cached_subtypes, \
                cached_direct_spec, cached_spec = cache

            if cache[:-1] == updated:
                return cached_spec

        dynamically_provided = [] if schema is None else [schema]
        dynamically_provided.extend(subtypes)

        # If we have neither a schema, nor a subtype, then we're also done.
        if not dynamically_provided:
            return spec

        dynamically_provided.append(spec)
        spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (spec, )

        return spec
Exemple #23
0
    def __get__(self, inst, cls=None):
        # We're looking at a class - fall back on default
        if inst is None:
            return getObjectSpecification(cls)
        
        # Find the data we need to know if our cache needs to be invalidated
        direct_spec = getattr(inst, '__provides__', None)
        portal_type = getattr(inst, 'portal_type', None)
        
        spec = direct_spec

        # If the instance doesn't have a __provides__ attribute, get the
        # interfaces implied by the class as a starting point.
        if spec is None:
            spec = implementedBy(cls)

        # If the instance has no portal type, then we're done.
        if portal_type is None:
            return spec

        fti = queryUtility(IDexterityFTI, name=portal_type)
        if fti is None:
            return spec

        schema = SCHEMA_CACHE.get(portal_type)
        subtypes = SCHEMA_CACHE.subtypes(portal_type)

        # Find the cached value. This calculation is expensive and called
        # hundreds of times during each request, so we require a fast cache
        cache = getattr(inst, '_v__providedBy__', None)
        updated = inst._p_mtime, schema, subtypes, direct_spec

        # See if we have a valid cache. Reasons to do this include:
        #
        #  - The schema was modified.
        #  - The subtypes were modified.
        #  - The instance was modified and persisted since the cache was built.
        #  - The instance has a different direct specification.
        if cache is not None:
            cached_mtime, cached_schema, cached_subtypes, \
                cached_direct_spec, cached_spec = cache

            if cache[:-1] == updated:
                return cached_spec

        dynamically_provided = [] if schema is None else [schema]
        dynamically_provided.extend(subtypes)

        # If we have neither a schema, nor a subtype, then we're also done.
        if not dynamically_provided:
            return spec

        dynamically_provided.append(spec)
        spec = Implements(*dynamically_provided)
        inst._v__providedBy__ = updated + (spec, )

        return spec
def migrate_to_pa_event(context):
    # Install plone.app.event
    context.runAllImportStepsFromProfile('profile-plone.app.event:default')
    # Re-import types to get newest Event type
    context.runImportStepFromProfile(
        'profile-plone.app.contenttypes:default',
        'typeinfo'
    )
    portal = getSite()
    migrate(portal, DXOldEventMigrator)
    SCHEMA_CACHE.clear()
Exemple #25
0
    def test_invalidate_cache(self):
        portal_type = u"testtype"
        fti = DexterityFTI(portal_type)
        SCHEMA_CACHE.get(portal_type)
        SCHEMA_CACHE.behavior_schema_interfaces(fti)
        self.assertIn('_v_schema_behavior_schema_interfaces',
                      fti.__dict__.keys())

        invalidate_cache(fti)
        self.assertNotIn('_v_schema_behavior_schema_interfaces',
                         fti.__dict__.keys())
Exemple #26
0
    def test_repeated_get_lookup(self):
        class ISchema(Interface):
            pass

        fti_mock = DexterityFTI(u"testtype")
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        schema1 = SCHEMA_CACHE.get(u"testtype")
        schema2 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is schema2 is ISchema)
    def test_repeated_get_lookup(self):

        class ISchema(Interface):
            pass

        fti_mock = DexterityFTI(u"testtype")
        fti_mock.lookupSchema = Mock(return_value=ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        schema1 = SCHEMA_CACHE.get(u"testtype")
        schema2 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is schema2 is ISchema)
 def setUp(self):
     self.portal = self.layer["portal"]
     setRoles(self.portal, TEST_USER_ID, ["Manager"])
     self.portal.invokeFactory("Folder", "test-folder")
     # Invalidate schema cache
     SCHEMA_CACHE.invalidate("Audio")
     SCHEMA_CACHE.invalidate("OGG Audio File")
     self.folder = self.portal["test-folder"]
     audio_id = self.folder.invokeFactory("Audio", "my-audio")
     self.audio = self.folder[audio_id]
     self.setup_content_data()
     self.audio.invokeFactory("OGG Audio File", "file.ogg")
     self.ogg_audio = self.audio["file.ogg"]
    def test_empty_name(self):

        # Mock FTI
        fti_mock = DexterityFTI(u"testtype")
        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('', u"foo"))
 def setUp(self):
     self.portal = self.layer['portal']
     with api.env.adopt_roles([
             'Manager',
     ]):
         self.folder = api.content.create(type='Folder',
                                          container=self.portal,
                                          id='test-folder')
         # Invalidate schema cache
         SCHEMA_CACHE.invalidate('ExternalContent')
         self.content = api.content.create(type='ExternalContent',
                                           container=self.folder,
                                           id='external')
         self.setup_content_data()
Exemple #31
0
    def test_unknown_type_not_cached(self):
        class ISchema1(Interface):
            pass

        fti = DexterityFTI(u"testtype")
        fti.lookupSchema = Mock(return_value=ISchema1)
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        schema1 = SCHEMA_CACHE.get(u"othertype")
        schema2 = SCHEMA_CACHE.get(u"testtype")
        schema3 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is None)
        self.assertTrue(schema2 is schema3 is ISchema1)
Exemple #32
0
    def test_empty_name(self):

        # Mock FTI
        fti_mock = DexterityFTI(u"testtype")
        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('', u"foo")
        )
    def test_repeated_lookup(self):
        class ISchema(Interface):
            pass

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        self.replay()

        schema1 = SCHEMA_CACHE.get(u"testtype")
        schema2 = SCHEMA_CACHE.get(u"testtype")

        self.failUnless(schema1 is schema2 is ISchema)
Exemple #34
0
    def test_repeated_get_lookup(self):
        class ISchema(Interface):
            pass

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ISchema)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        self.replay()

        schema1 = SCHEMA_CACHE.get(u"testtype")
        schema2 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is schema2 is ISchema)
Exemple #35
0
    def test_repeated_lookup_with_changed_schema(self):
        class ISchema1(Interface):
            pass

        class ISchema2(Interface):
            pass

        fti = DexterityFTI(u"testtype")
        fti.lookupSchema = Mock(side_effect=[ISchema1, ISchema2])
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        schema1 = SCHEMA_CACHE.get(u"testtype")
        schema2 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is schema2 and schema2 is ISchema1)
Exemple #36
0
    def test_unexistent_behaviors_lookup(self):
        fti = DexterityFTI(u"testtype")
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")
        # Set an unregistered behavior
        fti.behaviors = ["foo.bar"]

        with patch("warnings.warn") as mock_warnings:
            SCHEMA_CACHE.behavior_registrations(u'testtype')
            # Verify the warning has been issued
            mock_warnings.assert_called_once_with(
                ('No behavior registration found for behavior named '
                 '"foo.bar" for factory "testtype" - trying deprecated '
                 'fallback lookup (will be removed in 3.0)..."'),
                DeprecationWarning,
            )
 def setUp(self):
     self.portal = self.layer['portal']
     # Invalidate schema cache
     SCHEMA_CACHE.invalidate('ExternalContent')
     with api.env.adopt_roles(['Manager', ]):
         self.folder = api.content.create(
             type='Folder',
             container=self.portal,
             id='test-folder'
         )
         self.content = api.content.create(
             type='ExternalContent',
             container=self.folder,
             id='external'
         )
    def test_unknown_type_not_cached(self):

        class ISchema1(Interface):
            pass

        fti = DexterityFTI(u"testtype")
        fti.lookupSchema = Mock(return_value=ISchema1)
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        schema1 = SCHEMA_CACHE.get(u"othertype")
        schema2 = SCHEMA_CACHE.get(u"testtype")
        schema3 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is None)
        self.assertTrue(schema2 is schema3 is ISchema1)
Exemple #39
0
    def __getattr__(self, name):
        # python basics:  __getattr__ is only invoked if the attribute wasn't
        # found by __getattribute__
        #
        # optimization: sometimes we're asked for special attributes
        # such as __conform__ that we can disregard (because we
        # wouldn't be in here if the class had such an attribute
        # defined).
        # also handle special dynamic providedBy cache here.
        # Ignore also some other well known names like
        # Permission, Acquisition and AccessControl related ones.
        if (name.startswith('__') or name.startswith('_v')
                or name.endswith('_Permission')
                or name in ATTRIBUTE_NAMES_TO_IGNORE):
            raise AttributeError(name)

        # attribute was not found; try to look it up in the schema and return
        # a default
        value = _default_from_schema(self, SCHEMA_CACHE.get(self.portal_type),
                                     name)
        if value is not _marker:
            return value

        # do the same for each behavior
        assignable = get_assignable(self)
        if assignable is not None:
            for behavior_registration in assignable.enumerateBehaviors():
                if behavior_registration.interface:
                    value = _default_from_schema(
                        self, behavior_registration.interface, name)
                    if value is not _marker:
                        return value

        raise AttributeError(name)
Exemple #40
0
    def omitted_fields(self):
        """ Gets the omitted fields from the schema. May be specified like this:

        ISchema.setTaggedValue('seantis.dir.base.omitted', ['field1', 'field2'])
        """
        iface = SCHEMA_CACHE.get(self.form.portal_type)
        return iface.queryTaggedValue('seantis.dir.base.omitted', [])
Exemple #41
0
 def getRichTextFieldNames(self):
     """ see ISchema interface """
     schema = SCHEMA_CACHE.get(self.getportaltype())
     return [
         name for name, field in schema.namesAndDescriptions()
         if isinstance(field, RichText)
     ]
Exemple #42
0
    def __getattr__(self, name):
        # python basics:  __getattr__ is only invoked if the attribute wasn't
        # found by __getattribute__
        #
        # optimization: sometimes we're asked for special attributes
        # such as __conform__ that we can disregard (because we
        # wouldn't be in here if the class had such an attribute
        # defined).
        # also handle special dynamic providedBy cache here.
        if name.startswith('__') or name == '_v__providedBy__':
            raise AttributeError(name)

        # attribute was not found; try to look it up in the schema and return
        # a default
        value = _default_from_schema(self, SCHEMA_CACHE.get(self.portal_type),
                                     name)
        if value is not _marker:
            return value

        # do the same for each subtype
        assignable = IBehaviorAssignable(self, None)
        if assignable is not None:
            for behavior_registration in assignable.enumerateBehaviors():
                if behavior_registration.interface:
                    value = _default_from_schema(
                        self, behavior_registration.interface, name)
                    if value is not _marker:
                        return value

        raise AttributeError(name)
    def test_repeated_lookup_with_changed_schema(self):

        class ISchema1(Interface):
            pass

        class ISchema2(Interface):
            pass

        fti = DexterityFTI(u"testtype")
        fti.lookupSchema = Mock(side_effect=[ISchema1, ISchema2])
        self.mock_utility(fti, IDexterityFTI, name=u"testtype")

        schema1 = SCHEMA_CACHE.get(u"testtype")
        schema2 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is schema2 and schema2 is ISchema1)
Exemple #44
0
    def test_no_read_permission(self):

        # Mock schema model
        class ITestSchema(Interface):
            test = zope.schema.TextLine(title=u"Test")

        ITestSchema.setTaggedValue(READ_PERMISSIONS_KEY, dict(foo='foo.View'))

        # Mock FTI
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ITestSchema)
        self.expect(fti_mock.behaviors).result(tuple())

        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Mock permissions
        self.mock_utility(Permission(u'foo.View', u"View foo"), IPermission,
                          u'foo.View')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        # Check permission
        securityManager_mock = self.mocker.mock()
        self.expect(securityManager_mock.checkPermission("View foo",
                                                         item)).result(True)
        getSecurityManager_mock = self.mocker.replace(
            'AccessControl.getSecurityManager')
        self.expect(
            getSecurityManager_mock()).result(securityManager_mock).count(1)

        self.mocker.replay()

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('test', u"foo"))
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('foo', u"bar"))

        # Unknown attributes are allowed
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__(
                'random', u"stuff"))
Exemple #45
0
 def _get_schema(self, inst):
     portal_type = getattr(inst, 'portal_type', None)
     if portal_type is not None:
         try:
             return SCHEMA_CACHE.get(portal_type)
         except (ValueError, AttributeError,):
             pass
     return None
    def test_unknown_type_not_cached(self):
        class ISchema1(Interface):
            pass

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ISchema1)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        self.replay()

        schema1 = SCHEMA_CACHE.get(u"othertype")
        schema2 = SCHEMA_CACHE.get(u"testtype")
        schema3 = SCHEMA_CACHE.get(u"testtype")

        self.failUnless(schema1 is None)
        self.failUnless(schema2 is schema3 is ISchema1)
    def test_empty_name(self):

        # Mock FTI
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).count(0)
        self.expect(fti_mock.behaviors).count(0)
        self.mock_utility(fti_mock, IDexterityFTI, u"testtype")

        # Content item
        item = Item("test")
        item.portal_type = u"testtype"

        self.mocker.replay()

        SCHEMA_CACHE.clear()

        self.assertTrue(item.__allow_access_to_unprotected_subobjects__("", u"foo"))
Exemple #48
0
    def setUp(self):
        self.portal = self.layer["portal"]
        self.request = self.layer["request"]

        self.portal.invokeFactory(
            "Document",
            id="doc1",
        )

        fti = queryUtility(IDexterityFTI, name="Plone Site")
        if fti is not None:
            behavior_list = [a for a in fti.behaviors]
            behavior_list.append("volto.blocks")
            fti.behaviors = tuple(behavior_list)
            # Invalidating the cache is required for the FTI to be applied
            # on the existing object
            SCHEMA_CACHE.invalidate("Plone Site")
Exemple #49
0
 def _get_schema(self, inst):
     portal_type = getattr(inst, 'portal_type', None)
     if portal_type is not None:
         try:
             return SCHEMA_CACHE.get(portal_type)
         except (ValueError, AttributeError,):
             pass
     return None
Exemple #50
0
    def test_unknown_type_not_cached(self):
        class ISchema1(Interface):
            pass

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ISchema1)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        self.replay()

        schema1 = SCHEMA_CACHE.get(u"othertype")
        schema2 = SCHEMA_CACHE.get(u"testtype")
        schema3 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is None)
        self.assertTrue(schema2 is schema3 is ISchema1)
Exemple #51
0
    def test_readfile_mimetype_no_message_no_primary_field(self):
        class ITest(Interface):
            title = schema.TextLine()

        SCHEMA_CACHE.clear()
        fti_mock = DexterityFTI(u'testtype')
        fti_mock.lookupSchema = Mock(return_value=ITest)
        fti_mock.behaviors = []

        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        item = Item('item')
        item.portal_type = 'testtype'

        readfile = DefaultReadFile(item)

        self.assertEqual('text/plain', readfile.mimeType)
    def test_attribute_and_value_error_not_cached(self):

        class ISchema1(Interface):
            pass

        # FTI mock
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).throw(AttributeError)
        self.expect(fti_mock.lookupSchema()).throw(ValueError)
        self.expect(fti_mock.lookupSchema()).result(ISchema1)
        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        self.replay()

        schema1 = SCHEMA_CACHE.get(u"testtype")

        SCHEMA_CACHE.invalidate('testtype')
        schema2 = SCHEMA_CACHE.get(u"testtype")

        SCHEMA_CACHE.invalidate('testtype')
        schema3 = SCHEMA_CACHE.get(u"testtype")

        self.assertTrue(schema1 is None)
        self.assertTrue(schema2 is None)
        self.assertTrue(schema3 is ISchema1)
Exemple #53
0
    def test_no_read_permission(self):

        # Mock schema model
        class ITestSchema(Interface):
            test = zope.schema.TextLine(title=u"Test")
        ITestSchema.setTaggedValue(READ_PERMISSIONS_KEY, dict(foo='foo.View'))

        # Mock FTI
        fti_mock = DexterityFTI(u"testtype")
        fti_mock.lookupSchema = Mock(return_value=ITestSchema)
        fti_mock.behaviors = ()

        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Mock permissions
        self.mock_utility(
            Permission(u'foo.View', u"View foo"), IPermission, u'foo.View'
        )

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"
        item.test = u"foo"
        item.foo = u"bar"

        # Check permission
        security_manager_mock = Mock()
        security_manager_mock.checkPermission = Mock(return_value=True)
        from AccessControl import getSecurityManager
        self.patch_global(
            getSecurityManager, return_value=security_manager_mock)

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('test', u"foo")
        )
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('foo', u"bar")
        )

        # Unknown attributes are allowed
        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('random', u"stuff")
        )
Exemple #54
0
    def test_empty_name(self):

        # Mock FTI
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).count(0)
        self.expect(fti_mock.behaviors).count(0)
        self.mock_utility(fti_mock, IDexterityFTI, u'testtype')

        # Content item
        item = Item('test')
        item.portal_type = u"testtype"

        self.mocker.replay()

        SCHEMA_CACHE.clear()

        self.assertTrue(
            item.__allow_access_to_unprotected_subobjects__('', u"foo"))
Exemple #55
0
def iterSchemata(context):
    """Return an iterable containing first the object's schema, and then
    any form field schemata for any enabled behaviors.
    """
    main_schema = SCHEMA_CACHE.get(context.portal_type)
    if main_schema:
        yield main_schema
    for schema in getAdditionalSchemata(context=context):
        yield schema
Exemple #56
0
    def __getattr__(self, name):
        
        # attribute was not found; try to look it up in the schema and return
        # a default
        
        schema = SCHEMA_CACHE.get(self.portal_type)
        if schema is not None:
            field = schema.get(name, None)
            if field is not None:
                return deepcopy(field.default)

        # do the same for each subtype
        for schema in SCHEMA_CACHE.subtypes(self.portal_type):
            field = schema.get(name, None)
            if field is not None:
                return deepcopy(field.default)

        raise AttributeError(name)
Exemple #57
0
    def test_readfile_mimetype_no_message_no_primary_field(self):

        class ITest(Interface):
            title = schema.TextLine()

        SCHEMA_CACHE.clear()
        fti_mock = DexterityFTI(u'testtype')
        fti_mock.lookupSchema = Mock(return_value=ITest)
        fti_mock.behaviors = []

        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        item = Item('item')
        item.portal_type = 'testtype'

        readfile = DefaultReadFile(item)

        self.assertEqual('text/plain', readfile.mimeType)
Exemple #58
0
def iterSchemata(context):
    """Return an iterable containing first the object's schema, and then
    any form field schemata for any enabled behaviors.
    """
    main_schema = SCHEMA_CACHE.get(context.portal_type)
    if main_schema:
        yield main_schema
    for schema in getAdditionalSchemata(context=context):
        yield schema
    def test_readfile_mimetype_no_message_no_primary_field(self):
        class ITest(Interface):
            title = schema.TextLine()

        SCHEMA_CACHE.clear()
        fti_mock = self.mocker.proxy(DexterityFTI(u"testtype"))
        self.expect(fti_mock.lookupSchema()).result(ITest)
        self.expect(fti_mock.behaviors).result([])

        self.mock_utility(fti_mock, IDexterityFTI, name=u"testtype")

        item = Item("item")
        item.portal_type = "testtype"

        readfile = DefaultReadFile(item)

        self.replay()

        self.assertEqual("text/plain", readfile.mimeType)