def _register(name, category, schema, klass, title, description): ConfigletClass = configlettype.ConfigletType( str(name), schema, klass, title, description) interface.classImplements(ConfigletClass, schema) # register behavior for configlet bname = 'memphis.controlpanel-%s'%name # behavior bfactory = configlet.BehaviorFactory(name, bname) storage.registerBehavior( bname, schema, bfactory, schema = IConfigletData, title=title, description=description, configContext=None) # set additional attributes ConfigletClass.__category__ = category # configlet instance inst = ConfigletClass() # register configlet as utility config.registerUtility(inst, schema, '') # register configlet in control panel getUtility(IControlPanel).addConfiglet(inst) inst.__behavior__ = storage.getBehavior(schema)
def check_testcase_implements_trial_reporter(done=[]): if done: return from zope.interface import classImplements from twisted.trial.itrial import IReporter classImplements(TestCaseFunction, IReporter) done.append(1)
def __call__(aspect, origin=None, *args, **kw): if kw.get('pdb'): import pdb;pdb.set_trace() # if called without positional arg, return partially applied # aspect if origin is None: if not kw: raise NeedKw return Partial(aspect, **kw) workbench = Workbench(origin, **kw) Instructions(aspect)(workbench) #raise AspectCollision(instr.name, aspect, target) # in case of instances functions need to be bound # if not x_is_class and (type(instr) is types.FunctionType): # instr = instr.__get__(x) # build a new class, with the same name and bases as the # target class, but a new dictionary with the aspect applied. cls = workbench.type(workbench.name, workbench.baseclasses, workbench.dct) if ZOPE_INTERFACE_AVAILABLE: classImplements(cls, *tuple(implementedBy(aspect))) if isclass(origin): if type(cls) is AspectMeta and kw: return Partial(cls, **kw) return cls return cls()
def patch(): CMFCatalogTool.unindexObject = unindexObjectCMF setattr(CMFCatalogTool, '__old_unindexObject', original_unindexObjectCMF) CatalogMultiplex.unindexObject = unindexObject setattr(CatalogMultiplex, '__old_unindexObject', original_unindexObject) DefaultOrdering.moveObjectsByDelta = moveObjectsByDelta setattr(DefaultOrdering, '__old_moveObjectsByDelta', original_moveObjectsByDelta) PloneSite.moveObjectsByDelta = PloneSite_moveObjectsByDelta setattr(PloneSite, '__old_moveObjectsByDelta', original_PloneSite_moveObjectsByDelta) prefix = '__old_' for patch in patches: klass = patch.kls if not IElasticSearchCatalog.implementedBy(klass): patched[klass] = {} for name, method in patch.method_map.items(): classImplements(klass, IElasticSearchCatalog) old = getattr(klass, name, method) patched[klass][name] = old setattr(klass, prefix + name, old) setattr(klass, name, method) info('patched %s', str(getattr(klass, name)))
def execute(self, renderer, config, layer, name, macro, target, template, configuration, **kw): """Register a renderer. """ provides = (name == DEFAULT and interfaces.IStructuredDefaultRenderer or interfaces.IStructuredRenderer) renderer.__view_name__ = name renderer.__renderer_macro__ = macro templates = renderer.module_info.getAnnotation( 'grok.templates', None ) if configuration is not None: classImplements(renderer, interfaces.IConfigurableRenderer) if templates is not None: config.action( discriminator=None, callable=self.checkTemplates, args=(templates, renderer.module_info, renderer) ) for context in target: adapts = (context, layer) config.action( discriminator=('adapter', adapts, provides, name), callable=zope.component.provideAdapter, args=(renderer, adapts, provides, name), ) return True
def Portlet(name, class_=None, title='', description='', template=None, schema=None, **kw): cdict = {} cdict.update(kw) cdict['__name__'] = name cdict['title'] = title cdict['description'] = description if template: cdict['template'] = ViewPageTemplateFile(template) if class_ is not None: class_name = 'Portlet<%s:%s>'%(class_.__name__, name) else: class_name = 'Portlet<%s>'%name if class_ is None: bases = (PortletBase,) else: bases = (class_, PortletBase) PortletClass = type(str(class_name), bases, cdict) if schema is not None: for f_id in getFields(schema): if not hasattr(PortletClass, f_id): setattr(PortletClass, f_id, ConfigurationProperty(schema[f_id])) PortletClass.__schema__ = schema interface.classImplements(PortletClass, schema) return PortletClass
def create_interface_mock(interface_class): '''given a Zope Interface class return a Mock sub class that implements the given Zope interface class. Mock objects created from this InterfaceMock will have Attributes and Methods required in the Interface will not have Attributes or Methods that are not specified ''' # the init method, automatically spec the interface methods def init(self, *args, **kwargs): Mock.__init__(self, spec=interface_class.names(), *args, **kwargs) # subclass named '<interface class name>Mock' name = interface_class.__name__ + "Mock" # create the class object and provide the init method klass = types.TypeType(name, (Mock, ), {"__init__": init}) # the new class should implement the interface classImplements(klass, interface_class) return klass
def prepareContent(self): classImplements(ATNewsItem, ITestTaggable) provideAdapter(TestExtender, name=u"archetypes.schemaextender.test.adapter") self.portal.invokeFactory('News Item', 'taggable-news') self.taggable_news = getattr(self.portal, 'taggable-news')
def testNoViewOnClassicClassException(self): from zope.interface import Interface from types import ClassType class ClassicError: __metaclass__ = ClassType class IClassicError(Interface): pass classImplements(ClassicError, IClassicError) support.setDefaultViewName(IClassicError, 'name', self.presentation_type) view_text = 'You made a classic error ;-)' def _view(obj, request): return lambda: view_text component.provideAdapter( _view, (ClassicError, self.presentation_type), Interface, name='name') try: raise ClassicError except: pass self.publication.handleException( self.object, self.request, sys.exc_info(), retry_allowed=False) # check we don't get the view we registered self.failIf(''.join(self.request.response._result) == view_text) # check we do actually get something self.failIf(''.join(self.request.response._result) == '')
def PortletManager( name, class_=None, provides=(), title='', description='', schema=None, portlettype=IPortlet, **kw): # configuration schema if schema is None: schema = IPortletManagerConfiguration cdict = {} cdict.update(kw) cdict['__name__'] = name cdict['__schema__'] = schema cdict['title'] = title cdict['description'] = description cdict['portlettype'] = portlettype class_name = 'PortletManager<%s>'%name if class_ is None: bases = (PortletManagerBase,) else: bases = (class_, PortletManagerBase) ManagerClass = type(str(class_name), bases, cdict) if provides: interface.classImplements(ManagerClass, *provides) for f_id in getFields(schema): if not hasattr(ManagerClass, f_id): setattr(ManagerClass, f_id, ConfigurationProperty(schema[f_id])) interface.classImplements(ManagerClass, schema) return ManagerClass
def updateSchema(self): sch = getUtility(ISchemaType, self.__context__.oid) sch.spec = self.schema sch.Type.__schema__ = self.schema interface.classImplements(sch.Type, self.schema) self.model = unicode(supermodel.serializeSchema(self.schema))
def findViewletManager(self, name): managerObj = queryMultiAdapter((self.context, self.request, self), IViewletManager, name) if not managerObj: # Here's where we go totally off the deep end... # Since we can't find this viewlet manager with the basic (self.context, self.request, self) # multiadapter lookup, this must be some sort of custom manager, registered to other interfaces. # In order to find it, we need to do a bit of reverse engineering... # Since Plone's generic setup process for viewlets constrains us to one viewlet manager / name, # we're going to assume that the adapter with this name, and a provided interface that is or extends IViewletManger # is the one we're looking for. # So, start with a search of the adapter registry... reg = [reg for reg in getGlobalSiteManager().registeredAdapters() if reg.name == name][0] # So far, I think we're stuck with context and request being the first two interfaces. providedClasses = [self.context, self.request] # Now, we take a look at the required interfaces... # And create some dummy classes that implement them. for iface in reg.required[2:]: tempClass = classobj("dummy", (object,), {}) classImplements(tempClass, iface) providedClasses.append(tempClass()) # Now just do a basic multiadapter lookup using our new objects providing the correct interfaces... managerObj = queryMultiAdapter(tuple(providedClasses), reg.provided, name) return managerObj
def afterSetUp(self): """ After setup """ setSite(self.portal) provideAdapter(ThemeTaggableMerged) provideAdapter(AttributeAnnotations, provides=IAnnotations, adapts=[IThemeTaggable]) classImplements(ATNewsItem, IThemeTaggable) self.setRoles('Manager') wftool = self.portal.portal_workflow # create a swedish themecentre, an english feed folder and # a swedish feed self.portal.invokeFactory('Folder', id='svthemecentre') obj = self.portal.svthemecentre # turn the folder into a themecentre by calling the promote view # and setting a theme tag obj.unrestrictedTraverse('@@promote2ThemeCentre')() IThemeCentreSchema(obj).tags = 'climate' obj.setLanguage('sv') obj.intro.setLanguage('sv') wftool.doActionFor(obj, 'publish') obj.reindexObject() self.portal.invokeFactory('Folder', id='feedfolder') self.portal.feedfolder.setLanguage('en') self.portal.feedfolder.reindexObject() self.portal.portal_languages.addSupportedLanguage('sv') self.basic_auth = '%s:%s' % (default_user, default_password)
def afterSetUp(self): classImplements(ATDocument, IOrderable) # have to delete previously created content manually # because of test isolation problems if 'test' in self.portal: del self.portal['test'] transaction.commit()
def test_builtins(self): # Setup intspec = implementedBy(int) olddeclared = intspec.declared classImplements(int, I1) class myint(int): implements(I2) x = 42 self.assertEqual([i.getName() for i in providedBy(x)], ['I1']) x = myint(42) directlyProvides(x, I3) self.assertEqual([i.getName() for i in providedBy(x)], ['I3', 'I2', 'I1']) # cleanup intspec.declared = olddeclared classImplements(int) x = 42 self.assertEqual([i.getName() for i in providedBy(x)], [])
def apply_customization_workflow(name, ti): """Apply customizations, features as per configuration from a workflow. Must (currently) be run after db setup. """ # support to infer/get the domain class from the type key from bungeni.models import domain, orm def get_domain_kls(name): """Infer the target domain kls from the type key, following underscore naming to camel case convention. """ return getattr(domain, naming.camel(name)) # get the domain class, and associate with type kls = get_domain_kls(name) ti.domain_model = kls # We "mark" the domain class with IWorkflowed, to be able to # register/lookup adapters generically on this single interface. classImplements(kls, IWorkflowed) # dynamic features from workflow wf = ti.workflow # decorate/modify domain/schema/mapping as needed kls = domain.configurable_domain(kls, wf) orm.configurable_mappings(kls) # !+ following should be part of the domain.feature_audit(kls) logic if wf.has_feature("audit"): # create/set module-level dedicated auditor singleton for auditable kls bungeni.core.audit.set_auditor(kls)
def load_contenttype(_context, contenttype): conf = contenttype['config'] klass = contenttype['klass'] if 'schema' in conf: classImplements(klass, conf['schema']) Factory = resolve_dotted_name( conf.get('factory', 'guillotina.content.ResourceFactory') ) factory = Factory( klass, title='', description='', type_name=conf['type_name'], schema=resolve_dotted_name(conf.get('schema', Interface)), behaviors=[resolve_dotted_name(b) for b in conf.get('behaviors', []) or ()], add_permission=conf.get('add_permission') or DEFAULT_ADD_PERMISSION, allowed_types=conf.get('allowed_types', None) ) component.utility( _context, provides=IResourceFactory, component=factory, name=conf['type_name'], )
def infoClass(self, data, ds=False): '''build info class''' if ds == True: self.infoclass = type(self.infoname,(RRDDataSourceInfo,),data) else: self.infoclass = type(self.infoname,(ComponentInfo,),data) classImplements(self.infoclass,self.interfaceclass) self.info_path = "%s.info.%s" % (self.zenpackname, self.infoname) self.addClassData(self.infoname, self.info_path, self.infoclass)
def viewletManager( _context, name, permission, for_=Interface, layer=interfaces.IFlourishLayer, view=interfaces.IPageBase, provides=interfaces.IViewletManager, class_=ViewletManager, template=None, update='update', render='render', allowed_interface=(), allowed_attributes=(), **kwargs): bases = (class_, ) if not interfaces.IViewletManager.implementedBy(class_): bases = bases + (ViewletManager, ) class_ = type(class_.__name__, bases, {}) allowed_interface = (tuple(allowed_interface) + (interfaces.IViewletManager, )) if not provides.implementedBy(class_): classImplements(class_, provides) contentDirective( _context, name, permission, for_=for_, layer=layer, view=view, class_=class_, template=template, update=update, render=render, allowed_interface=allowed_interface, allowed_attributes=allowed_attributes, **kwargs)
def ViewModelType(name, class_=None, provides=(), title='', description='', schema=None, **kw): cdict = {} cdict.update(kw) cdict['__id__'] = name cdict['__name__'] = name cdict['__schema__'] = schema cdict['__title__'] = title cdict['__description__'] = description class_name = 'ViewModel<%s>'%name if class_ is None: bases = (ViewModel,) else: bases = (class_, ViewModel) ViewModelClass = type(str(class_name), bases, cdict) if provides: interface.classImplements(ViewModelClass, *provides) if schema is not None: for f_id in getFields(schema): if not hasattr(ViewModelClass, f_id) and \ f_id not in ('context', 'request'): setattr(ViewModelClass, f_id, StorageProperty(schema[f_id])) interface.classImplements(ViewModelClass, schema) return ViewModelClass
def testExceptionSideEffects(self): from zope.publisher.interfaces import IExceptionSideEffects @implementer(IExceptionSideEffects) class SideEffects(object): def __init__(self, exception): self.exception = exception def __call__(self, obj, request, exc_info): self.obj = obj self.request = request self.exception_type = exc_info[0] self.exception_from_info = exc_info[1] class SideEffectsFactory: def __call__(self, exception): self.adapter = SideEffects(exception) return self.adapter factory = SideEffectsFactory() from ZODB.POSException import ConflictError from zope.interface import Interface class IConflictError(Interface): pass classImplements(ConflictError, IConflictError) component.provideAdapter(factory, (IConflictError,), IExceptionSideEffects) exception = ConflictError() try: raise exception except: self.publication.handleException( self.object, self.request, sys.exc_info(), retry_allowed=False) adapter = factory.adapter self.assertEqual(exception, adapter.exception) self.assertEqual(exception, adapter.exception_from_info) self.assertEqual(ConflictError, adapter.exception_type) self.assertEqual(self.object, adapter.obj) self.assertEqual(self.request, adapter.request)
def new_custom_domain_model(type_key, domain_interface, archetype_key): domain_model_name = naming.model_name(type_key) assert archetype_key, \ "Custom descriptor %r does not specify an archetype" % (type_key) archetype = getattr(MODEL_MODULE, naming.model_name(archetype_key)) # AttributeError # !+ assert archetype constraints domain_model = type(domain_model_name, (archetype,), { "__module__": MODEL_MODULE.__name__, "extended_properties": [], } ) # apply domain_interface classImplements(domain_model, domain_interface) # set on MODEL_MODULE (register on type_info downstream) setattr(MODEL_MODULE, domain_model_name, domain_model) # db map custom domain class from sqlalchemy.orm import mapper mapper(domain_model, inherits=archetype, polymorphic_on=utils.get_local_table(archetype).c.type, polymorphic_identity=type_key, #naming.polymorphic_identity(domain_model), ) log.info("new_custom_domain_model [%s] %s.%s" % ( type_key, MODEL_MODULE.__name__, domain_model_name)) return domain_model
def feature_audit(kls): """Decorator for domain types to support "audit" feature. """ interface.classImplements(kls, interfaces.IFeatureAudit) # If a domain class is explicitly defined, then it is assumed that all # necessary setup is also taken care of. Typically, only the sub-classes # of an archetype (mapped to a same table) need dynamic creation/setup. def audit_cls_exists_for(auditable_cls): audit_cls_name = "%sAudit" % (auditable_cls.__name__) return bool(globals().get(audit_cls_name)) if not audit_cls_exists_for(kls): # define {kls}Audit class feature_audit.CREATED_AUDIT_CLASS_FOR.add(kls) def base_audit_class(kls): """Identify what should be the BASE audit class for a {kls}Audit class to inherit from, and return it. """ # !+ may have a deeper inheritance # !+ other archetypes if kls is not Doc and issubclass(kls, Doc): return DocAudit return Audit audit_kls = base_audit_class(kls).auditFactory(kls) globals()[audit_kls.__name__] = audit_kls # !+ITER_TYPE_INFO remember decorated classes, for audit.set_auditor(kls), # that is called quite early, and capi.iter_type_info() is not yet ready... feature_audit.DECORATED.add(kls) return kls
def generate_table_schema_interface(ti): '''!+DO_NOT_REORDER_USER_APPLIED_INTERFACES def get_domain_interfaces(domain_model): """Return the domain bases for an interface as well as a filtered implements only list (base interfaces removed). Note that for 2nd level (mapped) domain classes i.e. those that inherit from another domain class e.g. Event(Doc), Office(Group), OfficeMember(GroupMembership), an IIModelInterface-providing I*TableSchema interface had already been created (for base class) and assigned to the super class--and that interface will match as one of the domain_base interfaces here. """ domain_bases = [] domain_implements = [] for iface in interface.implementedBy(domain_model): if IIModelInterface.providedBy(iface): domain_bases.append(iface) else: domain_implements.append(iface) domain_bases = tuple(domain_bases) or (IAlchemistContent,) return domain_bases, domain_implements bases, implements = get_domain_interfaces(ti.domain_model) ''' # derived_table_schema: # - ALWAYS dynamically generated # - directlyProvides IIModelInterface (by virtue of IAlchemistContent) type_key = naming.polymorphic_identity(ti.domain_model) # use the class's mapper select table as input for the transformation table_schema_interface_name = naming.table_schema_interface_name(type_key) domain_table = utils.get_local_table(ti.domain_model) derived_table_schema = transmute( domain_table, annotation=ti.descriptor_model, interface_name=table_schema_interface_name, __module__=INTERFACE_MODULE.__name__, #_generated_by="bungeni.alchemist.catalyst.generate_table_schema_interface" #bases=bases) bases=(IAlchemistContent,)) # apply, register on type_info, set on module interface.classImplements(ti.domain_model, derived_table_schema) utils.inisetattr(ti, "derived_table_schema", derived_table_schema) setattr(INTERFACE_MODULE, table_schema_interface_name, derived_table_schema) log.info("generate_table_schema_interface: %s", derived_table_schema) # defensive sanity check - that derived_table_schema is precisely the FIRST # resolving IIModelInterface-providing interface implemented by domain_model # !+ this failing does not necessarily mean an incorrectness for iface in interface.implementedBy(ti.domain_model): if IIModelInterface.providedBy(iface): assert iface is derived_table_schema, (ti.domain_model, iface, id(iface), derived_table_schema, id(derived_table_schema)) break '''!+DO_NOT_REORDER_USER_APPLIED_INTERFACES
def _decorator(cls): missing = object() for interface in interfaces: classImplements(cls, interface) for name in interface: if getattr(cls, name, missing) is missing: setattr(cls, name, Passthrough(name, context)) return cls
def setUp(self): classImplements(TranslationDomain, IAttributeAnnotatable) self.sm = PlacefulSetup.setUp(self, site=True) TestITranslationDomain.setUp(self) setup.addUtility(self.sm, "default", ITranslationDomain, self._domain) ztapi.provideUtility(IFactory, Factory(MessageCatalog), "zope.app.MessageCatalog")
def load_vocabulary(_context, vocabulary): conf = vocabulary['config'] klass = vocabulary['klass'] from guillotina.schema.vocabulary import getVocabularyRegistry vocabulary_registry = getVocabularyRegistry() from guillotina.schema.interfaces import ISource classImplements(klass, ISource) vocabulary_registry.register(conf['name'], klass)
def setMappers(self): if not hasattr(self, 'metadata'): self.connect() classImplements(MetaData, IMetadata) notify(self.notifyInterface(self.metadata)) if self.createAll: self.metadata.create_all(checkfirst=True) self.configuredMappers = True
def setUp(test=None): browserSetUp(test) setup.setUpCalendaring() from schooltool.app.overlay import CalendarOverlayInfo from schooltool.app.app import ShowTimetables provideAdapter(ShowTimetables) classImplements(CalendarOverlayInfo, IAttributeAnnotatable)
def feature_event(kls): """Decorator for domain types to support "event" feature. For Doc types (other than Event itself). """ # domain.Event itself may NOT support events assert not interfaces.IEvent.implementedBy(kls) interface.classImplements(kls, interfaces.IFeatureEvent) return kls
def afterSetUp(self): base.EasyFormTestCase.afterSetUp(self) self.folder.invokeFactory('EasyForm', 'ff1') self.ff1 = getattr(self.folder, 'ff1') self.ff1.title = u'ff1' self.ff1.checkAuthenticator = False # no csrf protection actions = get_actions(self.ff1) actions['mailer'].recipient_email = u'*****@*****.**' set_actions(self.ff1, actions) self.mailhost = self.folder.MailHost self.mailhost._send = self.dummy_send classImplements(BaseRequest, IFormLayer)
def testNotImplemented(self): class C(object): pass class I(Interface): pass self.assertRaises(DoesNotImplement, verifyClass, I, C) classImplements(C, I) verifyClass(I, C)
def afterSetUp(self): base.EasyFormTestCase.afterSetUp(self) self.folder.invokeFactory('EasyForm', 'ff1') self.ff1 = getattr(self.folder, 'ff1') self.ff1.checkAuthenticator = False # no csrf protection classImplements(BaseRequest, IFormLayer) from collective.easyform.validators import update_validators update_validators() request = self.app.REQUEST for i in FORM_DATA: request.form['form.widgets.{0}'.format(i)] = FORM_DATA[i]
def test_ObjectSpecification(self): c = C() directlyProvides(c, I4) self.assertEqual([i.getName() for i in providedBy(c)], ['I4', 'I31', 'I1', 'I2']) self.assertEqual([i.getName() for i in providedBy(c).flattened()], ['I4', 'I31', 'I3', 'I1', 'I2', 'Interface']) self.assert_(I1 in providedBy(c)) self.failIf(I3 in providedBy(c)) self.assert_(providedBy(c).extends(I3)) self.assert_(providedBy(c).extends(I31)) self.failIf(providedBy(c).extends(I5)) class COnly(A, B): implementsOnly(I31) class D(COnly): implements(I5) classImplements(D, I5) c = D() directlyProvides(c, I4) self.assertEqual([i.getName() for i in providedBy(c)], ['I4', 'I5', 'I31']) self.assertEqual([i.getName() for i in providedBy(c).flattened()], ['I4', 'I5', 'I31', 'I3', 'Interface']) self.failIf(I1 in providedBy(c)) self.failIf(I3 in providedBy(c)) self.assert_(providedBy(c).extends(I3)) self.failIf(providedBy(c).extends(I1)) self.assert_(providedBy(c).extends(I31)) self.assert_(providedBy(c).extends(I5)) class COnly(A, B): __implemented__ = I31 class D(COnly): implements(I5) classImplements(D, I5) c = D() directlyProvides(c, I4) self.assertEqual([i.getName() for i in providedBy(c)], ['I4', 'I5', 'I31']) self.assertEqual([i.getName() for i in providedBy(c).flattened()], ['I4', 'I5', 'I31', 'I3', 'Interface']) self.failIf(I1 in providedBy(c)) self.failIf(I3 in providedBy(c)) self.assert_(providedBy(c).extends(I3)) self.failIf(providedBy(c).extends(I1)) self.assert_(providedBy(c).extends(I31)) self.assert_(providedBy(c).extends(I5))
def apply_customization_workflow(name): """Apply customizations, features as per configuration from a workflow. Must (currently) be run after db setup. """ # support to infer/get the domain class from the workflow name def camel(name): """Convert an underscore-separated word to CamelCase. """ return "".join([ s.capitalize() for s in name.split("_") ]) from bungeni.models import domain, schema, orm def get_domain_kls(workflow_name): """Infer a workflow's target domain kls from the workflow file name, following underscore naming to camel case convention; names that do not follow the convention are custom handled, as per mapping below. """ # !+ should state it explicitly as a param? # !+ problem with multiple types sharing same workflow e.g. # UserAddress, GroupAddress kls_name = camel( get_domain_kls.non_conventional.get(workflow_name, workflow_name)) return getattr(domain, kls_name) # !+RENAME_TO_CONVENTION get_domain_kls.non_conventional = { "address": "address", # !+ use common base cls for User & Group addresses "agendaitem": "agenda_item", "attachedfile": "attached_file", "tableddocument": "tabled_document", "groupsitting": "group_sitting", "membership": "group_membership", } # get the domain class kls = get_domain_kls(name) # We "mark" the domain class with IWorkflowed, to be able to # register/lookup adapters generically on this single interface. classImplements(kls, IWorkflowed) # dynamic features from workflow wf = get_workflow(name) def _apply_customization_workflow(kls): # decorate/modify domain/schema/mapping as needed kls = domain.configurable_domain(kls, wf) schema.configurable_schema(kls) orm.configurable_mappings(kls) # !+ ok to call set_auditor(kls) more than once? # !+ following should be part of the domain.auditable(kls) logic if wf.has_feature("audit"): # create/set module-level dedicated auditor singleton for auditable kls bungeni.core.audit.set_auditor(kls) if kls.__dynamic_features__: _apply_customization_workflow(kls)
def mark_error_retryable(error): """ Mark an exception instance or type as retryable. If this exception is caught by ``pyramid_retry`` then it may retry the request. """ if isinstance(error, Exception): alsoProvides(error, IRetryableError) elif inspect.isclass(error) and issubclass(error, Exception): classImplements(error, IRetryableError) else: raise ValueError( 'only exception objects or types may be marked retryable')
def feature_address(kls, **params): """Decorator for domain types to support "address" feature. For User and Group types, means support for possibility to have addresses. """ interface.classImplements(kls, interfaces.IFeatureAddress) if issubclass(kls, domain.Group): add_container_property_to_model( kls, "addresses", "bungeni.models.domain.GroupAddressContainer", "group_id") elif issubclass(kls, domain.User): add_container_property_to_model( kls, "addresses", "bungeni.models.domain.UserAddressContainer", "user_id")
def test_class_doesnt_implement_but_classImplements_later(self): from zope.interface import Interface from zope.interface import classImplements class ICurrent(Interface): pass class Current(object): pass classImplements(Current, ICurrent) self._callFUT(ICurrent, Current)
def test_implementedBy(self): class I2(I1): pass class C1(Odd): pass classImplements(C1, I2) class C2(C1): pass classImplements(C2, I3) self.assertEqual([i.getName() for i in implementedBy(C2)], ['I3', 'I2'])
def auditable(kls): """Decorator for auditable domain types, to collect in one place all that is needed for a domain type to be auditale. """ # assign interface (changes property added downstream) name = kls.__name__ interface.classImplements(kls, interfaces.IAuditable) CUSTOM_DECORATED["auditable"].add(kls) # define TYPEChange class change_name = "%sChange" % (name) change_kls = ItemChanges.makeChangeFactory(change_name) globals()[change_name] = change_kls return kls
def generate_container_class(ti): """Generate a zope3 container class for a domain model. """ type_key = naming.polymorphic_identity(ti.domain_model) container_name = naming.container_class_name(type_key) container_iname = naming.container_interface_name(type_key) base_interfaces = (IAlchemistContainer,) # logging variables msg = (ti.domain_model.__name__, CONTAINER_MODULE.__name__, container_name) # container class - if we already have one, exit if getattr(CONTAINER_MODULE, container_name, None): log.info("generate_container_class [model=%s] found container %s.%s, skipping" % msg) ti.container_class = getattr(CONTAINER_MODULE, container_name) return container_class = type(container_name, (AlchemistContainer,), dict(_class=ti.domain_model, __module__=CONTAINER_MODULE.__name__) ) # set on CONTAINER_MODULE, register on type_info setattr(CONTAINER_MODULE, container_name, container_class) ti.container_class = container_class log.info("generate_container_class [model=%s] generated container %s.%s" % msg) # container interface - if we already have one, skip creation # !+ should always be newly created? container_iface = getattr(INTERFACE_MODULE, container_iname, None) msg = (ti.domain_model.__name__, CONTAINER_MODULE.__name__, container_iname) if container_iface is not None: assert issubclass(container_iface, IAlchemistContainer) log.info("generate_container_class [model=%s] skipping container interface %s.%s for" % msg) else: container_iface = interface.interface.InterfaceClass( container_iname, bases=base_interfaces, __module__=INTERFACE_MODULE.__name__ ) # set on INTERFACE_MODULE, register on type_info setattr(INTERFACE_MODULE, container_iname, container_iface) ti.container_interface = container_iface log.info("generate_container_class [model=%s] generated container interface %s.%s" % msg) # setup security for n, d in container_iface.namesAndDescriptions(all=True): protectName(container_class, n, "zope.Public") # apply implementedBy if not container_iface.implementedBy(container_class): interface.classImplements(container_class, container_iface)
def apply_customization_workflow(type_key, ti): """Apply customizations, features as per configuration from a workflow. Must (currently) be run after db setup. """ domain_model, workflow = ti.domain_model, ti.workflow assert domain_model and workflow, ti # We "mark" the domain class with IWorkflowed, to be able to # register/lookup adapters generically on this single interface. #!+directlyImplementedBy? assert not IWorkflowed.implementedBy(domain_model), domain_model if not IWorkflowed.implementedBy(domain_model): classImplements(domain_model, IWorkflowed) # dynamic features from workflow - setup domain/mapping as needed for feature in workflow.features: feature.setup_model(domain_model)
def afterSetUp(self): self.folder.invokeFactory("EasyForm", "ff1") self.ff1 = getattr(self.folder, "ff1") self.ff1.CSRFProtection = False # no csrf protection self.ff1.showAll = True field_template = api.content.create(self.layer["portal"], "File", id="easyform_default_fields.xml") with open(join(dirname(__file__), "fixtures", self.schema_fixture)) as f: filecontent = NamedFile(f.read(), contentType="application/xml") field_template.file = filecontent classImplements(BaseRequest, IFormLayer) validators.update_validators()
def apply_concrete_behaviors(): ''' Configured behaviors for an object should always be applied and can't be removed. Should be called once at startup instead of doing alsoProvides every time an object is created ''' for type_name, factory in get_utilities_for(IResourceFactory): for behavior in factory.behaviors: behavior_registration = get_utility( IBehavior, name=behavior.__identifier__) if behavior_registration.marker is not None: classImplements(factory._callable, behavior_registration.marker)
def subscription_factory(cls, *args, **kwargs): """Utility which allows to to quickly register a subscription adapters which returns new instantiated objects of a given class >>> provideSubscriptionAdapter(subscription_factory(MetricsDaemonProcess), adapts=(IProc,)) """ class SubscriptionFactoryWrapper(object): def __new__(self, *_ignore): return cls(*args) interfaces = get_direct_interfaces(cls) classImplements(SubscriptionFactoryWrapper, *interfaces) return SubscriptionFactoryWrapper
def wire(cls, name, key, *interfaces, **options): fields = {} bases = (cls, ) + options.get('bases', ()) for iface in interfaces: for field in schema.getFields(iface).values(): fields[field.__name__] = property( lambda self, field=field: self.getFieldProperty(field), lambda self, value, field_name=field.__name__: self. setProperty(field_name, value)) new_class = type(name, bases, fields) cls.annotation_key = key classImplements(new_class, interfaces) return new_class
def enable_attachment(kls): """Decorator for attachment-feature of domain types. Executed on adapters.load_workflow() !+ currently assumes that the object is versionable. !+ domain.AttachedFile is the only versionable type that is not a PI. """ # !+ domain.AttachedFile is versionable, but does not support attachments assert kls is not AttachedFile # assign interface (versions property added downstream) name = kls.__name__ interface.classImplements(kls, interfaces.IAttachmentable) CUSTOM_DECORATED["enable_attachment"].add(kls) return kls
def versionable(kls): """Decorator for versionable domain types, to collect in one place all that is needed for a domain type to be versionable. Note: @versionable implies @auditable, here made explicit """ # if @versionable must also be @auditable: kls = auditable(kls) # assign interface (versions property added downstream) name = kls.__name__ interface.classImplements(kls, interfaces.IVersionable) # define TYPEVersion class version_name = "%sVersion" % (name) globals()[version_name] = ItemVersions.makeVersionFactory(version_name) return kls
def test_classImplements(self): class A(Odd): implements(I3) class B(Odd): implements(I4) class C(A, B): pass classImplements(C, I1, I2) self.assertEqual([i.getName() for i in implementedBy(C)], ['I1', 'I2', 'I3', 'I4']) classImplements(C, I5) self.assertEqual([i.getName() for i in implementedBy(C)], ['I1', 'I2', 'I5', 'I3', 'I4'])
def load_adapter(_context, adapter): conf = adapter['config'] klass = resolve_dotted_name(adapter['klass']) factory = conf.pop('factory', None) or klass _component_conf(conf) if 'provides' in conf and isinstance(klass, type): # not sure if this is what we want or not for sure but # we are automatically applying the provides interface to # registered class objects classImplements(klass, conf['provides']) component.adapter( _context, factory=(factory,), **conf )
def registerImplementation(self, klass, adapter=NO_ADAPTER_NEEDED, depth=1): if adapter is NO_ADAPTER_NEEDED: zi.classImplements(klass, self.subject) elif adapter is DOES_NOT_SUPPORT: ifaces = zi.Declaration( [i.__iro__ for i in zi.implementedBy(klass)]) - self.subject zi.classImplementsOnly(klass, ifaces) return supermeta(ZopeInterfaceAsProtocol, self).registerImplementation(klass, adapter, depth)
def afterSetUp(self): super(TestFunctions, self).afterSetUp() self.folder.invokeFactory('EasyForm', 'ff1') self.ff1 = getattr(self.folder, 'ff1') self.ff1.title = u'ff1' self.mailhost = self.folder.MailHost self.mailhost._send = self.dummy_send self.request = makerequest(self.app).REQUEST self.ff1.CSRFProtection = False self.ff1.actions_model = (self.ff1.actions_model.replace( u'<description>E-Mails Form Input</description>', u'<recipient_email>[email protected]</recipient_email><description>E-Mails Form Input</description>' )) self.mailhost = self.folder.MailHost self.mailhost._send = self.dummy_send classImplements(BaseRequest, IFormLayer)
def classImplements(class_, *interfaces): normalized_interfaces = [] for i in interfaces: normalized_interfaces.append(i) return interface.classImplements( class_, # NOQA: D001 *normalized_interfaces)
def patchPersistent(): global _patched if _patched: return _patched = True from zope.interface import classImplements from Persistence import Persistent from App.interfaces import IPersistentExtra for k, v in PersistentUtil.__dict__.items(): if k[0] != '_': setattr(Persistent, k, v) classImplements(Persistent, IPersistentExtra)
def patch(): prefix = '__old_' for patch in patches: klass = patch.kls if not IElasticSearchCatalog.implementedBy(klass): patched[klass] = {} for name, method in patch.method_map.items(): classImplements(klass, IElasticSearchCatalog) old = getattr(klass, name, method) patched[klass][name] = old setattr(klass, prefix + name, old) setattr(klass, name, method) info('patched %s', str(getattr(klass, name))) CatalogMultiplex.unindexObject = unindexObject setattr(CatalogMultiplex, '__old_unindexObject', original_unindexObject)
def annotation_proxy(context, schema): annotations = IAnnotations(context) properties = dict( (name, AnnotationProperty(annotations, schema[name])) for name in schema ) properties['portal_url'] = staticmethod(context.portal_url) proxy = type( "%sAdapter" % schema.__name__[1:], (object, ), properties, ) classImplements(proxy, schema) return proxy()
def _add_delegate(cls): """Returns the given class, updated with a new __init__ function that wraps the old one and adds instantiation of the delegate, and adds new member functions that match the public members in the delegate class. Any public members in the delegate that have a name matching anything in the scoping object are ignored. """ member_set = set() for klass in getmro(cls): member_set.update(klass.__dict__.keys()) listofdels = [] for tup in delegates: if isinstance(tup, tuple): delegatename, delegate = tup else: # assume no name given delegate = tup delegatename = None if not isinstance(delegate, type): raise TypeError( "Can't add delegate to class %s because delegate is not a class" % cls.__name__) if not delegatename: delegatename = '_%s' % delegate.__name__.lower() listofdels.append((delegatename, delegate)) alldict = {} for interface in implementedBy(delegate): classImplements(cls, interface) for klass in getmro(delegate): if hasattr(klass, '_do_not_promote'): skip = klass._do_not_promote else: skip = [] for k, v in getmembers(klass, ismethod): if not k.startswith( '_' ) and k not in alldict and k not in member_set and k not in skip: member_set.add(k) setattr(cls, k, forwarder(cls, v, delegatename)) cls.__init__ = init_wrapper(cls, listofdels) return cls
def testExceptionSideEffects(self): from zope.publisher.interfaces import IExceptionSideEffects class SideEffects(object): implements(IExceptionSideEffects) def __init__(self, exception): self.exception = exception def __call__(self, obj, request, exc_info): self.obj = obj self.request = request self.exception_type = exc_info[0] self.exception_from_info = exc_info[1] class SideEffectsFactory: def __call__(self, exception): self.adapter = SideEffects(exception) return self.adapter factory = SideEffectsFactory() from ZODB.POSException import ConflictError from zope.interface import Interface class IConflictError(Interface): pass classImplements(ConflictError, IConflictError) component.provideAdapter(factory, (IConflictError, ), IExceptionSideEffects) exception = ConflictError() try: raise exception except: pass self.publication.handleException(self.object, self.request, sys.exc_info(), retry_allowed=False) adapter = factory.adapter self.assertEqual(exception, adapter.exception) self.assertEqual(exception, adapter.exception_from_info) self.assertEqual(ConflictError, adapter.exception_type) self.assertEqual(self.object, adapter.obj) self.assertEqual(self.request, adapter.request)
def setup_model(self, model): """Executed on adapters.load_workflow(). """ self.validate_model(model) if self.enabled: interface.classImplements(model, self.feature_interface) # add a convenient "{name}_feature" (cached) property to model feature_name = self.name feature_property_name = "%s_feature" % (feature_name) assert feature_property_name not in model.__dict__, \ "Model %s already has an attribute %r" % ( model, feature_property_name) def _get_feature(self): return get_feature(self, feature_name) _get_feature.__name__ = feature_property_name setattr(model, feature_property_name, misc.cached_property(_get_feature)) # additional model preparations self.decorate_model(model)
def ViewletManagerFactory(name, interface, bases=(), cdict=None): # pylint: disable=invalid-name """Viewlet manager factory""" attr_dict = {'__name__': name} attr_dict.update(cdict or {}) if ViewletManager not in bases: # Make sure that we do not get a default viewlet manager mixin, if the # provided base is already a full viewlet manager implementation. # pylint: disable=no-value-for-parameter if not (len(bases) == 1 and IViewletManager.implementedBy(bases[0])): bases = bases + (ViewletManager, ) viewlet_manager_class = type( '<ViewletManager providing %s>' % interface.getName(), bases, attr_dict) classImplements(viewlet_manager_class, interface) return viewlet_manager_class