def test_provider(self): from z3c.pt.pagetemplate import ViewPageTemplateFile class Context(object): pass class Request(object): response = None class View(object): __call__ = ViewPageTemplateFile("provider.pt") from zope.interface import Interface from zope.schema import Field from zope.interface import implementer from zope.interface import directlyProvides from zope.contentprovider.interfaces import ITALNamespaceData class ITestProvider(Interface): context = Field(u"Provider context.") directlyProvides(ITestProvider, ITALNamespaceData) assert ITALNamespaceData.providedBy(ITestProvider) @implementer(ITestProvider) class Provider(object): def __init__(self, *args): data.extend(list(args)) def update(self): data.extend("updated") def render(self): return """<![CDATA[ %r, %r]]>""" % ( data, self.__dict__) view = View() data = [] from zope.interface import implementedBy from zope.component import provideAdapter from zope.contentprovider.interfaces import IContentProvider provideAdapter( Provider, ( implementedBy(Context), implementedBy(Request), implementedBy(View) ), IContentProvider, name="content" ) context = Context() request = Request() result = view(context=context, request=request) self.failUnless(repr(data) in result) self.failUnless(repr({'context': context}) in result)
def test_transportInterfaces(self): """ The transport wrapper passed to the wrapped protocol's C{makeConnection} provides the same interfaces as are provided by the original transport. """ class IStubTransport(Interface): pass class StubTransport: implements(IStubTransport) # Looking up what ProtocolWrapper implements also mutates the class. # It adds __implemented__ and __providedBy__ attributes to it. These # prevent __getattr__ from causing the IStubTransport.providedBy call # below from returning True. If, by accident, nothing else causes # these attributes to be added to ProtocolWrapper, the test will pass, # but the interface will only be provided until something does trigger # their addition. So we just trigger it right now to be sure. implementedBy(policies.ProtocolWrapper) proto = protocol.Protocol() wrapper = policies.ProtocolWrapper(policies.WrappingFactory(None), proto) wrapper.makeConnection(StubTransport()) self.assertTrue(IStubTransport.providedBy(proto.transport))
def test_provider(self): class Context(object): pass class Request(object): response = None class View(object): __call__ = ViewPageTemplateFile("provider.pt") # Test binding descriptor behaviour. self.assertIsInstance(View.__call__, ViewPageTemplateFile) from zope.interface import Interface from zope.schema import Field from zope.interface import implementer from zope.interface import directlyProvides from zope.contentprovider.interfaces import ITALNamespaceData class ITestProvider(Interface): context = Field(u"Provider context.") directlyProvides(ITestProvider, ITALNamespaceData) assert ITALNamespaceData.providedBy(ITestProvider) @implementer(ITestProvider) class Provider(object): def __init__(self, *args): data.extend(list(args)) def update(self): data.extend("updated") def render(self): return """<![CDATA[ %r, %r]]>""" % (data, self.__dict__) view = View() data = [] from zope.interface import implementedBy from zope.component import provideAdapter from zope.contentprovider.interfaces import IContentProvider provideAdapter( Provider, ( implementedBy(Context), implementedBy(Request), implementedBy(View), ), IContentProvider, name="content", ) context = Context() request = Request() result = view(context=context, request=request) self.assertIn(repr(data), result) self.assertIn(repr({"context": context}), result)
def testInterfaces(self): types_tool = self.portal.portal_types # a new interface class IForTest(Interface): pass from Products.ERP5Type import interfaces interfaces.IForTest = IForTest # one new type dummy_type = types_tool.newContent('InterfaceTestType', 'Base Type') # implementing IForTest dummy_type.edit(type_class='Person', type_interface_list=['IForTest',],) transaction.commit() from erp5.portal_type import InterfaceTestType # it's necessary to load the class # to have a correct list of interfaces implemented_by = list(implementedBy(InterfaceTestType)) self.failIf(IForTest in implemented_by) InterfaceTestType.loadClass() implemented_by = list(implementedBy(InterfaceTestType)) self.assertTrue(IForTest in implemented_by, 'IForTest not in %s' % implemented_by) InterfaceTestType.restoreGhostState() implemented_by = list(implementedBy(InterfaceTestType)) self.failIf(IForTest in implemented_by)
def test_pickle_zodb_lookup_utility(self): # Now, we can register a couple utilities in the base, save everything, # and look it up in the sub (when the classes don't match) storage = DemoStorage() self._store_base_subs_in_zodb(storage) db = DB(storage) conn = db.open() new_base = conn.root()['base'] new_base._p_activate() new_sub = conn.root()['sub'] new_base.utilities.btree_provided_threshold = 0 new_base.utilities.btree_map_threshold = 0 new_base.registerUtility(MockSite(), provided=IFoo) provided1 = new_base.adapters._provided # Previously this would fail. Now it works. new_base.registerUtility(MockSite(), provided=implementedBy(object), name=u'foo') new_base.registerUtility(MockSite(), provided=IMock, name=u'foo') provided2 = new_base.adapters._provided # Make sure that it only converted once assert_that(provided1, is_(same_instance(provided2))) assert_that(new_base._utility_registrations, is_(BTrees.OOBTree.OOBTree)) assert_that(new_base._utility_registrations.keys(), contains( (IFoo, u''), (IMock, u'foo'), (implementedBy(object), u'foo'), )) assert_that(new_base.utilities._provided, is_(BTrees.family64.OI.BTree)) assert_that(new_base.utilities._adapters[0], is_(BTrees.family64.OO.BTree)) assert_that(new_base.utilities._adapters[0][IFoo], is_(BTrees.family64.OO.BTree)) transaction.commit() conn.close() db.close() db = DB(storage) conn = db.open() new_sub = conn.root()['sub'] x = new_sub.queryUtility(IFoo) assert_that(x, is_(MockSite)) x = new_sub.queryUtility(IMock, u'foo') assert_that(x, is_(MockSite))
def __init__(self, module, name, klass): self.__parent__ = module self.__name__ = name self.__klass = klass # Setup interfaces that are implemented by this class. self.__interfaces = tuple(implementedBy(klass)) self.__all_ifaces = tuple(implementedBy(klass).flattened()) # Register the class with the global class registry. classRegistry[self.getPath()] = klass
def test_register_implemented_by_lookup_utility(self): storage = DemoStorage() self._store_base_subs_in_zodb(storage) db = DB(storage) conn = db.open() new_base = conn.root()['base'] new_base._p_activate() new_sub = conn.root()['sub'] new_base.utilities.btree_provided_threshold = 0 new_base.utilities.btree_map_threshold = 0 new_base.registerUtility(MockSite(), provided=IFoo) provided1 = new_base.adapters._provided # In the past, we couldn't register by implemented, but now we can. new_base.registerUtility(MockSite(), provided=implementedBy(MockSite), name=u'foo') provided2 = new_base.adapters._provided # Make sure that it only converted once assert_that(provided1, is_(same_instance(provided2))) assert_that(new_base._utility_registrations, is_(BTrees.OOBTree.OOBTree)) assert_that(new_base._utility_registrations.keys(), contains( (IFoo, u''), ((implementedBy(MockSite), u'foo')), )) assert_that(new_base.utilities._provided, is_(BTrees.family64.OI.BTree)) assert_that(new_base.utilities._adapters[0], is_(BTrees.family64.OO.BTree)) assert_that(new_base.utilities._adapters[0][IFoo], is_(BTrees.family64.OO.BTree)) transaction.commit() conn.close() db.close() db = DB(storage) conn = db.open() new_sub = conn.root()['sub'] x = new_sub.queryUtility(IFoo) assert_that(x, is_(MockSite)) # But it can't actually be looked up, regardless of whether we # convert to btrees or not x = new_sub.queryUtility(MockSite, u'foo') assert_that(x, is_(none()))
def testUtil(self): self.assert_(IC in implementedBy(C)) self.assert_(I1 in implementedBy(A)) self.assert_(not I1 in implementedBy(C)) self.assert_(I2 in implementedBy(B)) self.assert_(not I2 in implementedBy(C)) self.assert_(IC in providedBy(C())) self.assert_(I1 in providedBy(A())) self.assert_(not I1 in providedBy(C())) self.assert_(I2 in providedBy(B())) self.assert_(not I2 in providedBy(C()))
def register(implementor, orig, *interfaceClasses): if orig in fakeimplementeds: origInterface = fakeimplementeds[orig] elif not isinstance(orig, InterfaceClass): origInterface = implementedBy(orig) else: origInterface = orig if not interfaceClasses: interfaceClasses = tuple(implementedBy(implementor)) for interfaceClass in interfaceClasses: registry.register([origInterface], interfaceClass, '', implementor)
def register(implementor, orig, *target_interfaces): """ Register an implementor to map from one interface to another .. python:: from zope.interface import implementer # implement*e*r is a typo in zope.interface, unfortunately @implementer(ITarget) class Implementor(stuff): stuff register(Implementor, IOriginal) .. python:: from zope.interface import implementer @implementer(ITarget1) @implementer(ITarget2) @implementer(INotTarget) class Implementor(stuff): stuff register(Implementor, IOriginal, ITarget1, ITarget2, ITargetNotImplemented) :Parameters: implementor Factory which returns an object which provides the target interface; if no interfaces are passed in, then the target interfaces will be inferred from the list of interfaces that the implementor implements. Note that this means that if you pass in any target interfaces, they will override the inferred ones orig Interface or class to map from. If it's a class, it must implement exactly one interface. target_interfaces zero or more target interfaces to map to """ if orig in fakeimplementeds: orig_interface = fakeimplementeds[orig] elif not isinstance(orig, InterfaceClass): orig_interface = implementedBy(orig) else: orig_interface = orig if not target_interfaces: target_interfaces = tuple(implementedBy(implementor)) for target_interface in target_interfaces: registry.register([orig_interface], target_interface, '', implementor) return implementor
def test_add_inheriteddelegatei(self): @add_delegate(InheritedDelegateI) class Delegator2(object): def __init__(self): self.x = 1 mems = set([n for n, v in getmembers(Delegator2, ismethod) if not n.startswith("_")]) self.assertEqual(mems, set(["i"])) interfaces = list(implementedBy(Delegator2)) self.assertEqual(interfaces, list(implementedBy(InheritedDelegateI))) delegator = Delegator2() for interface in interfaces: self.assertTrue(obj_has_interface(delegator, interface)) self.assertEqual(delegator.i(delegator.x), 2)
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 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 test_add_delegatej(self): @add_delegate(DelegateJ) class Delegator1(object): def __init__(self): self.x = 1 mems = set([n for n, v in getmembers(Delegator1, ismethod) if not n.startswith("_")]) self.assertEqual(mems, set(["i", "j"])) interfaces = list(implementedBy(Delegator1)) self.assertEqual(interfaces, list(implementedBy(DelegateJ))) delegator = Delegator1() for interface in interfaces: self.assertTrue(obj_has_interface(delegator, interface)) self.assertEqual(delegator.i(delegator.x), 2) self.assertEqual(delegator.j(delegator.x), 3)
def bindClass( klass, mapper=None ): """ attach validation to a sqlalchemy mapped class, based on its implemented schemas, via property validators, taking care to wrap sqlalchemy properties. """ if mapper is None: mapper = getattr( klass, 'mapper') # compile the klass mapper, this will add instrumented attributes to the class # we could alternatively do.. mapper.compile() compiles all extant mappers mapper.compile() # find all the model schemas implemented by the class for iface in interface.implementedBy( klass ): if not IIModelInterface.providedBy( iface ): continue # for any field in the schema, see if we have an sa property for field_name in schema.getFieldNames( iface ): v = klass.__dict__.get( field_name ) # if so then wrap it in a field property if not isinstance( v, attributes.InstrumentedAttribute): continue field = iface[ field_name ] vproperty = ValidatedProperty( field, v, field_name ) setattr( klass, field_name, vproperty )
def test_it_with_dotted_renderer(self): from zope.interface import implementedBy from pyramid.threadlocal import get_current_registry from pyramid.interfaces import IRequest from pyramid.interfaces import IView from pyramid.interfaces import IViewClassifier from pyramid.exceptions import Forbidden from pyramid.configuration import Configurator context = DummyContext() reg = get_current_registry() config = Configurator(reg) def dummy_renderer_factory(*arg, **kw): return lambda *arg, **kw: 'OK' config.add_renderer('.pt', dummy_renderer_factory) def view(request): return {} self._callFUT(context, view, renderer='fake.pt') actions = context.actions regadapt = actions[0] register = regadapt['callable'] register() derived_view = reg.adapters.lookup( (IViewClassifier, IRequest, implementedBy(Forbidden)), IView, default=None) self.assertNotEqual(derived_view, None) self.assertEqual(derived_view(None, None).body, 'OK') self.assertEqual(derived_view.__name__, 'bwcompat_view')
def _getAdapterProvided(factory): provided = list(implementedBy(factory)) if len(provided) == 1: return provided[0] raise TypeError( "The adapter factory doesn't implement a single interface " "and no provided interface was specified.")
def test_it(self): from zope.interface import implementedBy from pyramid.threadlocal import get_current_registry from pyramid.interfaces import IRequest from pyramid.interfaces import IView from pyramid.interfaces import IViewClassifier from pyramid.exceptions import Forbidden context = DummyContext() def view(request): return 'OK' self._callFUT(context, view) actions = context.actions self.assertEqual(len(actions), 1) discrim = ('view', Forbidden, '', None, IView, None, None, None, None, None, False, None, None, None) regadapt = actions[0] self.assertEqual(regadapt['discriminator'], discrim) register = regadapt['callable'] register() reg = get_current_registry() derived_view = reg.adapters.lookup( (IViewClassifier, IRequest, implementedBy(Forbidden)), IView, default=None) self.assertNotEqual(derived_view, None) self.assertEqual(derived_view(None, None), 'OK') self.assertEqual(derived_view.__name__, 'bwcompat_view')
def register(template=template): if isinstance(template, basestring): helper = renderers.RendererHelper(name=template, package=config.package, registry=config.registry) template = helper.renderer.implementation() layout_intr.update(dict(name=name, filename=template.filename, context=context, callable=layout)) introspectables.append(layout_intr) def derived_layout(context, request): wrapped = layout(context, request) wrapped.__layout__ = name wrapped.__template__ = template return wrapped r_context = context if r_context is None: r_context = Interface if not IInterface.providedBy(r_context): r_context = implementedBy(r_context) reg_layout = config.registry.adapters.lookup((r_context,), ILayout, name=name) if isinstance(reg_layout, _MultiLayout): reg_layout[containment] = derived_layout return elif containment: reg_layout = _MultiLayout(reg_layout) reg_layout[containment] = derived_layout else: reg_layout = derived_layout config.registry.registerAdapter(reg_layout, (context,), ILayout, name=name)
def _getAdapterRequired(factory, required): if required is None: try: required = factory.__component_adapts__ except AttributeError: raise TypeError( "The adapter factory doesn't have a __component_adapts__ " "attribute and no required specifications were specified" ) elif ISpecification.providedBy(required): raise TypeError("the required argument should be a list of " "interfaces, not a single interface") result = [] for r in required: if r is None: r = Interface elif not ISpecification.providedBy(r): if isinstance(r, class_types): r = implementedBy(r) else: raise TypeError("Required specification must be a " "specification or class." ) result.append(r) return tuple(result)
def utility(_context, provides=None, component=None, factory=None, name=''): if factory and component: raise TypeError("Can't specify factory and component.") if provides is None: if factory: provides = list(implementedBy(factory)) else: provides = list(providedBy(component)) if len(provides) == 1: provides = provides[0] else: raise TypeError("Missing 'provides' attribute") if factory: kw = dict(factory=factory) else: # older component registries don't accept factory as a kwarg, # so if we don't need it, we don't pass it kw = {} try: registry = _context.registry except AttributeError: # pragma: no cover (b/c) registry = get_current_registry() _context.action( discriminator = ('utility', provides, name), callable = registry.registerUtility, args = (component, provides, name, _context.info), kw = kw, )
def classDoesNotImplement(class_, *interfaces): # convert any Zope 2 interfaces to Zope 3 using fromZ2Interface interfaces = flatten(interfaces) implemented = implementedBy(class_) for iface in interfaces: implemented = implemented - iface return zope.interface.classImplementsOnly(class_, implemented)
def _create_service_mock(self, service_name): # set self.clients if not already set clients = Mock(name='clients') base_service = get_service_registry().get_service_base(service_name) # Save it to use in test_verify_service self.base_service = base_service self.addCleanup(delattr, self, 'base_service') dependencies = base_service.dependencies for dep_name in dependencies: dep_service = get_service_registry().get_service_base(dep_name) # Force mock service to use interface mock_service = Mock(name='clients.%s' % dep_name, spec=dep_service) setattr(clients, dep_name, mock_service) # set self.dep_name for convenience setattr(self, dep_name, mock_service) self.addCleanup(delattr, self, dep_name) iface = list(implementedBy(dep_service))[0] names_and_methods = iface.namesAndDescriptions() for func_name, _ in names_and_methods: mock_func = mocksignature(getattr(dep_service, func_name), mock=Mock(name='clients.%s.%s' % (dep_name, func_name)), skipfirst=True) setattr(mock_service, func_name, mock_func) return clients
def utility(_context, provides=None, component=None, factory=None, name=''): if factory and component: raise TypeError("Can't specify factory and component.") if provides is None: if factory: provides = list(implementedBy(factory)) else: provides = list(providedBy(component)) if len(provides) == 1: provides = provides[0] else: raise TypeError("Missing 'provides' attribute") if name == '': if factory: name = getName(factory) else: name = getName(component) _context.action( discriminator=('utility', provides, name), callable=handler, args=('registerUtility', component, provides, name), kw=dict(factory=factory)) _context.action( discriminator=None, callable=provide_interface, args=('', provides))
def registerPlugin(self, plugin): """Registers a plugin.""" plugin_types = { 'presence': IPresencePlugin, 'chat': IChatPlugin, 'population': IPopulationPlugin, 'base_plugin': BaseInterface, } # Everything is, at least, a base plugin. valid_types = ['baseplugin'] # Loop through the types of plugins and check for implentation of each. claimed_compliances = list(implementedBy(type(plugin))) # Can we use this as a map instead? for t, interface in plugin_types.iteritems(): if interface in claimed_compliances: try: verifyObject(interface, plugin) # If the above succeeded, then `plugin` implementes `interface`. self.plugins[t].append(plugin) self.plugins[t].sort() valid_types.append(t) except DoesNotImplement: log.error('Plugin %s claims to be a %s, but is not!', plugin.name, t) plugin.setup(self) log.info('registered plugin %s as %s', plugin.name, valid_types)
def widget(self, _context, field, **kw): attrs = kw class_ = attrs.pop("class_", None) # Try to do better than accepting the string value by looking through # the interfaces and trying to find the field, so that we can use # 'fromUnicode()' if isinstance(class_, type): ifaces = implementedBy(class_) for name, value in kw.items(): for iface in ifaces: if name in iface: attrs[name] = iface[name].fromUnicode(value) break if class_ is None: # The _default_widget_factory is required to allow the # <widget> directive to be given without a "class" # attribute. This can be used to override some of the # presentational attributes of the widget implementation. class_ = self._default_widget_factory # don't wrap a factory into a factory if IWidgetFactory.providedBy(class_): factory = class_ else: factory = CustomWidgetFactory(class_, **attrs) self._widgets[field+'_widget'] = factory
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 cached value and return it if possible cached = getattr(inst, '_v__providedBy__', None) if cached is not None: return cached # Get interfaces directly provided by the draft proxy provided = getattr(inst, '__provides__', None) # If the draft proxy doesn't have a __provides__ attribute, get the # interfaces implied by the class as a starting point. if provided is None: provided = implementedBy(cls) # Add the interfaces provided by the target target = aq_base(inst._DraftProxy__target) if target is None: return provided provided += providedBy(target) inst._v__providedBy__ = provided return provided
def get_dataflow(self, pathname): ''' Get the structure of the specified assembly or of the global namespace if no pathname is specified; consists of the list of components and the connections between them (i.e., the dataflow). ''' dataflow = {} if pathname and len(pathname) > 0: try: asm, root = self.get_object(pathname) if has_interface(asm, IAssembly): dataflow = asm.get_dataflow() except Exception as err: self._error(err, sys.exc_info()) else: components = [] for k, v in self.proj.items(): if is_instance(v, Component): inames = [cls.__name__ for cls in list(implementedBy(v.__class__))] components.append({ 'name': k, 'pathname': k, 'type': type(v).__name__, 'interfaces': inames, 'python_id': id(v) }) dataflow['components'] = components dataflow['connections'] = [] dataflow['parameters'] = [] dataflow['constraints'] = [] dataflow['objectives'] = [] dataflow['responses'] = [] return json.dumps(dataflow, default=json_default)
def interfaces_implementedBy_class_for(obj): """Dump out list of interfaces implementedBy an object's class.""" return """ interfaces implementedBy %s: %s""" % (obj.__class__, "\n ".join( ["%s %s"%(i, id(i)) for i in interface.implementedBy(obj.__class__)] or [ "</>" ] ))
def _get_components(self,cont,pathname=None): ''' get a heierarchical list of all the components in the given container or dictionary. the name of the root container, if specified, is prepended to all pathnames ''' comps = [] for k,v in cont.items(): if is_instance(v,Component): comp = {} if cont == self.proj.__dict__: comp['pathname'] = k children = self._get_components(v,k) else: comp['pathname'] = pathname+'.'+ k if pathname else k children = self._get_components(v,comp['pathname']) if len(children) > 0: comp['children'] = children comp['type'] = str(v.__class__.__name__) inames = [] for klass in list(implementedBy(v.__class__)): inames.append(klass.__name__) comp['interfaces'] = inames comps.append(comp) return comps
def register_adapter(config, cls, from_, to_=None, name=None): to_ = to_ or list(implementedBy(cls))[0] name = name or cls.mimetype config.registry.registerAdapter(cls, (from_, ), to_, name=name)
def payload(self): if type(self.item) is tuple: return tuple(sorted(self.item)) return tuple(sorted(implementedBy(self.item)))
def includeme(config): """register adapters """ specs = [] for rsc in RESOURCES: # each resource is available ... name, interface = rsc.name, rsc.interface # ... as json cls = type('Json%s' % rsc.model.mapper_name(), (Json, ), {}) config.registry.registerAdapter(cls, (interface, ), interfaces.IRepresentation, name=Json.mimetype) if rsc.with_index: # ... as html index specs.append((interface, Index, 'text/html', 'html', name + '/index_html.mako', {})) # ... as html details page specs.append((interface, Representation, 'text/html', 'html', name + '/detail_html.mako', {})) # ... as html snippet (if the template exists) specs.append( (interface, Representation, 'application/vnd.clld.snippet+xml', 'snippet.html', name + '/snippet_html.mako', {})) # ... as RDF in various notations for notation in RDF_NOTATIONS.values(): specs.append((interface, Rdf, notation.mimetype, notation.extension, name + '/rdf.mako', { 'rdflibname': notation.name })) # ... as RDF collection index rdf_xml = RDF_NOTATIONS['xml'] specs.append((interface, RdfIndex, rdf_xml.mimetype, rdf_xml.extension, 'index_rdf.mako', { 'rdflibname': rdf_xml.name })) # citeable resources are available as html page listing available metadata formats: for _if in [interfaces.IContribution, interfaces.IDataset]: specs.append((_if, Representation, 'application/vnd.clld.md+xml', 'md.html', 'md_html.mako', {})) specs.extend([ (interfaces.ILanguage, Index, 'application/vnd.google-earth.kml+xml', 'kml', 'clld:web/templates/language/kml.mako', { 'send_mimetype': 'application/xml' }), (interfaces.ILanguage, Representation, 'application/vnd.google-earth.kml+xml', 'kml', 'clld:web/templates/language/kml.pt', { 'send_mimetype': 'application/xml' }), (interfaces.IContribution, Index, 'text/html', 'html', 'contribution/index_html.mako', {}), ]) for i, spec in enumerate(specs): interface, base, mimetype, extension, template, extra = spec extra.update(mimetype=mimetype, extension=extension, template=template) cls = type('Renderer%s' % i, (base, ), extra) config.registry.registerAdapter(cls, (interface, ), list(implementedBy(base))[0], name=mimetype) for cls in [BibTex, TxtCitation, ReferenceManager]: for if_ in [interfaces.IRepresentation, interfaces.IMetadata]: for adapts in [interfaces.IContribution, interfaces.IDataset]: config.registry.registerAdapter(cls, (adapts, ), if_, name=cls.mimetype) config.registry.registerAdapter(GeoJsonLanguages, (interfaces.ILanguage, ), interfaces.IIndex, name=GeoJson.mimetype) config.registry.registerAdapter(GeoJsonParameter, (interfaces.IParameter, ), interfaces.IRepresentation, name=GeoJson.mimetype) config.include(biblio)
def get_dataflow(self): ''' Get a dictionary of components and the connections between them that make up the data flow for the assembly; also includes parameter, constraint, and objective flows ''' components = [] connections = [] parameters = [] constraints = [] objectives = [] if is_instance(self, Assembly): # list of components (name & type) in the assembly g = self._depgraph._graph names = [ name for name in nx.algorithms.dag.topological_sort(g) if not name.startswith('@') ] # Bubble-up drivers ahead of their parameter targets. sorted_names = [] for name in names: comp = self.get(name) if is_instance(comp, Driver) and hasattr(comp, '_delegates_'): driver_index = len(sorted_names) for dname, dclass in comp._delegates_.items(): inst = getattr(comp, dname) if isinstance(inst, HasParameters): refs = inst.get_referenced_compnames() for ref in refs: try: target_index = sorted_names.index(ref) except ValueError: pass else: driver_index = min(driver_index, target_index) sorted_names.insert(driver_index, name) else: sorted_names.append(name) # Process names in new order. for name in sorted_names: comp = self.get(name) if is_instance(comp, Component): inames = [ cls.__name__ for cls in list(implementedBy(comp.__class__)) ] components.append({ 'name': comp.name, 'pathname': comp.get_pathname(), 'type': type(comp).__name__, 'valid': comp.is_valid(), 'interfaces': inames, 'python_id': id(comp) }) if is_instance(comp, Driver): if hasattr(comp, '_delegates_'): for name, dclass in comp._delegates_.items(): inst = getattr(comp, name) if isinstance(inst, HasParameters): for name, param in inst.get_parameters().items( ): if isinstance(param, ParameterGroup): for n, p in zip( name, tuple(param.targets)): parameters.append( [comp.name + '.' + n, p]) else: parameters.append([ comp.name + '.' + name, param.target ]) elif isinstance(inst, (HasConstraints, HasEqConstraints, HasIneqConstraints)): for path in inst.get_referenced_varpaths(): name, dot, rest = path.partition('.') constraints.append( [path, comp.name + '.' + rest]) elif isinstance(inst, (HasObjective, HasObjectives)): for path in inst.get_referenced_varpaths(): name, dot, rest = path.partition('.') objectives.append( [path, comp.name + '.' + name]) # list of connections (convert tuples to lists) conntuples = self.list_connections(show_passthrough=True) for connection in conntuples: connections.append(list(connection)) return { 'components': components, 'connections': connections, 'parameters': parameters, 'constraints': constraints, 'objectives': objectives }
def implementedBy(object): warnings.warn( "This module is deprecated, use zope.interface directly instead", DeprecationWarning, stacklevel=2) return zi.implementedBy(object)
def get_private_site(self): return utils.get_private_site(self.portal) def set_private_site(self, value): utils.set_private_site(self.portal, value) SecurityControlPanelAdapter.get_private_site = get_private_site SecurityControlPanelAdapter.set_private_site = set_private_site SecurityControlPanelAdapter.private_site = property( SecurityControlPanelAdapter.get_private_site, SecurityControlPanelAdapter.set_private_site ) # re-register adapter with new interface _decl = implementedBy(SecurityControlPanelAdapter) _decl -= ISecuritySchema _decl += IPrivateSiteSchema classImplementsOnly(SecurityControlPanelAdapter, _decl.interfaces()) del _decl getGlobalSiteManager().registerAdapter(SecurityControlPanelAdapter) # re-instanciate form SecurityControlPanel.form_fields = FormFields(IPrivateSiteSchema)
def _getAdapterProvided(factory): provided = list(implementedBy(factory)) if len(provided) == 1: return provided[0] raise TypeError("The adapter factory doesn't implement a single interface " "and no provided interface was specified.")
def uninstallSiteHooks(): for class_ in _localsite_monkies: delattr(class_, 'getSiteManager') delattr(class_, 'setSiteManager') classImplementsOnly(class_, implementedBy(class_) - IPossibleSite) _localsite_monkies.remove(class_)
'query adapter (all trivial registrations, deep inheritance)', bench_query_adapter, populate_components(), [DeepestInheritance()], inner_loops=1) runner.bench_time_func( 'sort interfaces', bench_sort, ifaces, inner_loops=INNER, ) runner.bench_time_func( 'sort implementedBy', bench_sort, [implementedBy(p) for p in implementers], inner_loops=INNER, ) runner.bench_time_func( 'sort mixed', bench_sort, [implementedBy(p) for p in implementers] + ifaces, inner_loops=INNER, ) runner.bench_time_func('contains (empty dict)', bench_in, {}, inner_loops=INNER) runner.bench_time_func('contains (populated dict: interfaces)',
def registerClass(self, instance_class=None, meta_type='', permission=None, constructors=(), icon=None, permissions=None, legacy=(), visibility="Global", interfaces=_marker, container_filter=None): """Register a constructor Keyword arguments are used to provide meta data: instance_class -- The class of the object that will be created. This is not currently used, but may be used in the future to increase object mobility. meta_type -- The kind of object being created This appears in add lists. If not specified, then the class meta_type will be used. permission -- The permission name for the constructors. If not specified, then a permission name based on the meta type will be used. constructors -- A list of constructor methods A method can me a callable object with a __name__ attribute giving the name the method should have in the product, or the method may be a tuple consisting of a name and a callable object. The method must be picklable. The first method will be used as the initial method called when creating an object. icon -- The name of an image file in the package to be used for instances. Note that the class icon attribute will be set automagically if an icon is provided. permissions -- Additional permissions to be registered If not provided, then permissions defined in the class will be registered. legacy -- A list of legacy methods to be added to ObjectManager for backward compatibility visibility -- "Global" if the object is globally visible, None else interfaces -- a list of the interfaces the object supports container_filter -- function that is called with an ObjectManager object as the only parameter, which should return a true object if the object is happy to be created in that container. The filter is called before showing ObjectManager's Add list, and before pasting (after object copy or cut), but not before calling an object's constructor. """ pack = self.__pack initial = constructors[0] productObject = self.__prod pid = productObject.id if icon and instance_class is not None: setattr(instance_class, 'icon', 'misc_/%s/%s' % (pid, os.path.split(icon)[1])) if permissions: if isinstance(permissions, basestring): # You goofed it! raise TypeError, ('Product context permissions should be a ' 'list of permissions not a string', permissions) for p in permissions: if isinstance(p, tuple): p, default = p registerPermissions(((p, (), default), )) else: registerPermissions(((p, ()), )) ############################################################ # Constructor permission setup if permission is None: permission = "Add %ss" % (meta_type or instance_class.meta_type) if isinstance(permission, tuple): permission, default = permission else: default = ('Manager', ) pr = PermissionRole(permission, default) registerPermissions(((permission, (), default), )) ############################################################ OM = ObjectManager for method in legacy: if isinstance(method, tuple): name, method = method aliased = 1 else: name = method.__name__ aliased = 0 if name not in OM.__dict__: setattr(OM, name, method) setattr(OM, name + '__roles__', pr) if aliased: # Set the unaliased method name and its roles # to avoid security holes. XXX: All "legacy" # methods need to be eliminated. setattr(OM, method.__name__, method) setattr(OM, method.__name__ + '__roles__', pr) if isinstance(initial, tuple): name, initial = initial else: name = initial.__name__ fd = getattr(pack, '__FactoryDispatcher__', None) if fd is None: class __FactoryDispatcher__(FactoryDispatcher): "Factory Dispatcher for a Specific Product" fd = pack.__FactoryDispatcher__ = __FactoryDispatcher__ if not hasattr(pack, '_m'): pack._m = AttrDict(fd) m = pack._m if interfaces is _marker: if instance_class is None: interfaces = () else: interfaces = tuple(implementedBy(instance_class)) Products.meta_types = Products.meta_types + ( { 'name': meta_type or instance_class.meta_type, # 'action': The action in the add drop down in the ZMI. This is # currently also required by the _verifyObjectPaste # method of CopyContainers like Folders. 'action': ('manage_addProduct/%s/%s' % (pid, name)), # 'product': Used by ProductRegistry for TTW products and by # OFS.Application for refreshing products. # This key might not be available. 'product': pid, # 'permission': Guards the add action. 'permission': permission, # 'visibility': A silly name. Doesn't have much to do with # visibility. Allowed values: 'Global', None 'visibility': visibility, # 'interfaces': A tuple of oldstyle and/or newstyle interfaces. 'interfaces': interfaces, 'instance': instance_class, 'container_filter': container_filter }, ) m[name] = initial m[name + '__roles__'] = pr for method in constructors[1:]: if isinstance(method, tuple): name, method = method else: name = os.path.split(method.__name__)[-1] if name not in productObject.__dict__: m[name] = method m[name + '__roles__'] = pr if icon: name = os.path.split(icon)[1] icon = ImageFile(icon, self.__pack.__dict__) icon.__roles__ = None if not hasattr(misc_, pid): setattr(misc_, pid, Misc_(pid, {})) getattr(misc_, pid)[name] = icon
def deregister(implementor, orig, *target_interfaces): "exact opposite of register()" if not target_interfaces: target_interfaces = tuple(implementedBy(implementor)) register(None, orig, *target_interfaces)