def test_import_site_with_subfolders_and_preserve(self): from Products.GenericSetup.utils import _getDottedName self._setUpAdapters() site = _makeFolder('site') site._setObject('foo', _makeFolder('foo')) foo = site._getOb('foo') foo._setObject('bar', _makeFolder('bar')) bar = foo._getOb('bar') context = DummyImportContext(site) # We want to add 'baz' to 'foo', without losing 'bar' context._files['structure/.objects' ] = 'foo,%s' % _getDottedName(foo.__class__) context._files['structure/.preserve'] = '*' context._files['structure/foo/.objects' ] = 'baz,%s' % _getDottedName(bar.__class__) context._files['structure/foo/.preserve'] = '*' context._files['structure/foo/baz/.objects'] = '' importer = self._getImporter() importer(context) self.assertEqual(len(site.objectIds()), 1) self.assertEqual(site.objectIds()[0], 'foo') self.assertEqual(len(foo.objectIds()), 2, site.foo.objectIds()) self.assertEqual(foo.objectIds()[0], 'bar') self.assertEqual(foo.objectIds()[1], 'baz')
def _extractSubscriptionAdapters(self): fragment = self._doc.createDocumentFragment() registrations = [ {'factory': _getDottedName(reg.factory), 'provided': _getDottedName(reg.provided), 'required': reg.required} for reg in self.context.registeredSubscriptionAdapters() ] registrations.sort(key=itemgetter('factory')) registrations.sort(key=itemgetter('provided')) blacklist = self._constructBlacklist() for reg_info in registrations: if reg_info['provided'] in blacklist: continue child = self._doc.createElement('subscriber') for_ = u'' for interface in reg_info['required']: for_ = for_ + _getDottedName(interface) + u'\n ' child.setAttribute('factory', reg_info['factory']) child.setAttribute('provides', reg_info['provided']) child.setAttribute('for', for_.strip()) fragment.appendChild(child) return fragment
def test__getDottedName_unicode( self ): from Products.GenericSetup.utils import _getDottedName dotted = u'%s' % _TEST_FUNC_NAME self.assertEqual( _getDottedName( dotted ), _TEST_FUNC_NAME ) self.assertEqual( type( _getDottedName( dotted ) ), str )
def _extractUtilities(self): fragment = self._doc.createDocumentFragment() registrations = [ {'component': reg.component, 'factory' : getattr(reg, 'factory', None), 'provided': _getDottedName(reg.provided), 'name': reg.name} for reg in self.context.registeredUtilities() ] registrations.sort(key=itemgetter('name')) registrations.sort(key=itemgetter('provided')) site = aq_base(self._getSite()) blacklist = self._constructBlacklist() for reg_info in registrations: if reg_info['provided'] in blacklist: continue child = self._doc.createElement('utility') child.setAttribute('interface', reg_info['provided']) if reg_info['name']: child.setAttribute('name', reg_info['name']) if reg_info['factory'] is not None: factory = _getDottedName(reg_info['factory']) child.setAttribute('factory', factory) else: factory = None comp = reg_info['component'] # check if the component is acquisition wrapped. If it is, export # an object reference instead of a factory reference if getattr(comp, 'aq_base', None) is not None: if aq_base(comp) is site: child.setAttribute('object', '') elif hasattr(aq_base(comp), 'getId'): child.setAttribute('object', comp.getId()) else: # This is a five.localsitemanager wrapped utility factory = _getDottedName(type(aq_base(comp))) child.setAttribute('factory', factory) else: factory = _getDottedName(type(comp)) child.setAttribute('factory', factory) if factory is not None: ofs_id = self._ofs_id(child) name = getattr(comp, '__name__', None) if ofs_id != name: if name is not None: child.setAttribute('id', name) else: child.setAttribute('id', ofs_id) fragment.appendChild(child) return fragment
def _extractPortletManagerNode(self, portletManagerRegistration): r = portletManagerRegistration child = self._doc.createElement('portletmanager') if r.component.__class__ is not PortletManager: child.setAttribute('class', _getDottedName(r.component.__class__)) child.setAttribute('name', r.name) specificInterface = providedBy(r.component).flattened().next() if specificInterface != IPortletManager: child.setAttribute('type', _getDottedName(specificInterface)) return child
def testRegisteredInterfaces(self): portlet = getUtility(IPortletType, name='portlets.Navigation') registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEqual( ['plone.app.portlets.interfaces.IColumn'], registered_interfaces)
def test_import_site_with_subitems(self): from Products.GenericSetup.utils import _getDottedName from faux_objects import KNOWN_INI from faux_objects import TestINIAware dotted = _getDottedName(TestINIAware) self._setUpAdapters() ITEM_IDS = ('foo', 'bar', 'baz') site = _makeFolder('site') context = DummyImportContext(site) # We want to add 'baz' to 'foo', without losing 'bar' context._files['structure/.objects'] = '\n'.join( ['%s,%s' % (x, dotted) for x in ITEM_IDS]) for index in range(len(ITEM_IDS)): id = ITEM_IDS[index] context._files[ 'structure/%s.ini' % id] = KNOWN_INI % ('Title: %s' % id, 'xyzzy', ) importer = self._getImporter() importer(context) after = site.objectIds() self.assertEqual(len(after), len(ITEM_IDS)) for found_id, expected_id in zip(after, ITEM_IDS): self.assertEqual(found_id, expected_id)
def testRegisteredInterfaces(self): portlet = getUtility(IPortletType, name='portlets.Events') registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEquals(['plone.app.portlets.interfaces.IColumn', 'plone.app.portlets.interfaces.IDashboard'], registered_interfaces)
def test_export_site_with_subfolders(self): from Products.GenericSetup.utils import _getDottedName self._setUpAdapters() FOLDER_IDS = ('foo', 'bar', 'baz') site = _makeFolder('site') site.title = 'AAA' site._setProperty('description', 'BBB') aside = _makeFolder('aside') dotted = _getDottedName(aside.__class__) for id in FOLDER_IDS: folder = _makeFolder(id) folder.title = 'Title: %s' % id site._setObject(id, folder) context = DummyExportContext(site) exporter = self._getExporter() exporter(context) self.assertEqual(len(context._wrote), 2 + (2 *len(FOLDER_IDS))) filename, text, content_type = context._wrote[0] self.assertEqual(filename, 'structure/.objects') self.assertEqual(content_type, 'text/comma-separated-values') objects = [x for x in reader(StringIO(text))] self.assertEqual(len(objects), 3) for index in range(len(FOLDER_IDS)): id = FOLDER_IDS[index] self.assertEqual(objects[index][0], id) self.assertEqual(objects[index][1], dotted) filename, text, content_type = context._wrote[2 + (2 * index)] self.assertEqual(filename, '/'.join(('structure', id, '.objects'))) self.assertEqual(content_type, 'text/comma-separated-values') subobjects = [x for x in reader(StringIO(text))] self.assertEqual(len(subobjects), 0) filename, text, content_type = context._wrote[2 + (2 * index) + 1] self.assertEqual(filename, '/'.join(('structure', id, '.properties'))) self.assertEqual(content_type, 'text/plain') parser = ConfigParser() parser.readfp(StringIO(text)) defaults = parser.defaults() self.assertEqual(len(defaults), 1) self.assertEqual(defaults['title'], 'Title: %s' % id) filename, text, content_type = context._wrote[1] self.assertEqual(filename, 'structure/.properties') self.assertEqual(content_type, 'text/plain') parser = ConfigParser() parser.readfp(StringIO(text)) defaults = parser.defaults() self.assertEqual(len(defaults), 2) self.assertEqual(defaults['title'], 'AAA') self.assertEqual(defaults['description'], 'BBB')
def test_import_site_with_subfolders(self): from Products.GenericSetup.utils import _getDottedName self._setUpAdapters() FOLDER_IDS = ('foo', 'bar', 'baz') site = _makeFolder('site') dotted = _getDottedName(site.__class__) context = DummyImportContext(site) for id in FOLDER_IDS: context._files['structure/%s/.objects' % id] = '' context._files['structure/%s/.properties' % id] = ( _PROPERTIES_TEMPLATE % id ) _ROOT_OBJECTS = '\n'.join(['%s,%s' % (id, dotted) for id in FOLDER_IDS]) context._files['structure/.objects'] = _ROOT_OBJECTS context._files['structure/.properties'] = ( _PROPERTIES_TEMPLATE % 'Test Site') importer = self._getImporter() importer(context) content = site.objectValues() self.assertEqual(len(content), len(FOLDER_IDS))
def testRegisteredInterfaces(self): portlet = getUtility(IPortletType, name="portlets.Calendar") registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEquals( ["plone.app.portlets.interfaces.IColumn", "plone.app.portlets.interfaces.IDashboard"], registered_interfaces )
def test_registered_interfaces(self): portlet = queryUtility(IPortletType, name="collective.polls.VotePortlet") registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEqual( ["plone.app.portlets.interfaces.IColumn", "plone.app.portlets.interfaces.IDashboard"], registered_interfaces )
def _constructBlacklist(self): blacklist = set((BLACKLIST_SELF, )) utils = getUtilitiesFor(IComponentsHandlerBlacklist) for _, util in utils: names = [_getDottedName(i) for i in util.getExcludedInterfaces()] blacklist.update(names) return blacklist
def test_RegisteredInterfaces(self): portlet = getUtility(IPortletType, name='vnccollab.redmine.portlets.RedmineTicketsPortlet') registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEquals(['plone.app.portlets.interfaces.IColumn', 'plone.app.portlets.interfaces.IDashboard'], registered_interfaces)
def test_registered_interfaces(self): sb_portlet = queryUtility(IPortletType, name='sc.social.bookmarks.sb_portlet') registered_interfaces = [_getDottedName(i) for i in sb_portlet.for_] registered_interfaces.sort() self.assertEqual(['plone.app.portlets.interfaces.IColumn', 'plone.app.portlets.interfaces.IDashboard'], registered_interfaces)
def deriveSettingsFromSnapshots(self, before, after): actions = [a for a in (after['actions'] - before['actions'])] adapters = [] if len(after['adapters']) > len(before['adapters']): registrations = [reg for reg in after['adapters'] if reg not in before['adapters']] # TODO: expand this to actually cover adapter registrations utilities = [] if len(after['utilities']) > len(before['utilities']): registrations = [reg for reg in after['utilities'] if reg not in before['utilities']] for registration in registrations: utilities.append( (_getDottedName(registration.provided), registration.name) ) settings = dict( types=[t for t in after['types'] if t not in before['types']], skins=[s for s in after['skins'] if s not in before['skins']], actions=actions, workflows=[ w for w in after['workflows'] if w not in before['workflows'] ], portalobjects=[ a for a in after['portalobjects'] if a not in before['portalobjects'] ], leftslots=[ s for s in after['leftslots'] if s not in before['leftslots'] ], rightslots=[ s for s in after['rightslots'] if s not in before['rightslots'] ], adapters=adapters, utilities=utilities, registrypredicates=[ s for s in after['registrypredicates'] if s not in before['registrypredicates'] ], ) jstool = getToolByName(self, 'portal_javascripts', None) if jstool is not None: settings['resources_js'] = [ r for r in after['resources_js'] if r not in before['resources_js'] ] settings['resources_css'] = [ r for r in after['resources_css'] if r not in before['resources_css'] ] return settings
def test_registered_interfaces(self): portlet = getUtility(IPortletType, name='brasil.gov.portlets.audiogallery') registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEqual( ['plone.app.portlets.interfaces.IColumn', 'plone.app.portlets.interfaces.IDashboard'], registered_interfaces )
def test_registered_interfaces(self): portlet = getUtility(IPortletType, name=self.name) registered_interfaces = [_getDottedName(i) for i in portlet.for_] expected = [ 'plone.app.portlets.interfaces.IColumn', 'plone.app.portlets.interfaces.IDashboard', ] self.assertItemsEqual(registered_interfaces, expected)
def export(self, export_context, subdir, root=False): context = self.context if not root: subdir = '%s/%s' % (subdir, context.getId()) stream = BytesIO() csv_writer = writer(stream) exportable = self.listExportableItems() for object_id, obj, adapter_ in exportable: # noinspection PyUnresolvedReferences if hasattr(Acquisition.aq_base(obj), 'getPortalTypeName'): csv_writer.writerow((object_id, obj.getPortalTypeName())) else: factory_namer = IContentFactoryName(obj, None) if factory_namer is None: factory_name = _getDottedName(obj.__class__) else: factory_name = factory_namer() csv_writer.writerow((object_id, factory_name)) export_context.writeDataFile('.objects', text=stream.getvalue(), content_type='text/comma-separated-values', # noqa subdir=subdir, ) prop_adapter = IINIAware(context, None) parser = ConfigParser() if prop_adapter is not None: parser.readfp(BytesIO(prop_adapter.as_ini())) title = context.Title() description = context.Description() title_str = encode_if_needed(title, 'utf-8') description_str = encode_if_needed(description, 'utf-8') parser.set('DEFAULT', 'Title', title_str) parser.set('DEFAULT', 'Description', description_str) stream = BytesIO() parser.write(stream) export_context.writeDataFile('.properties', text=stream.getvalue(), content_type='text/plain', subdir=subdir, ) for object_id, obj, adapter_ in exportable: if adapter_ is not None: adapter_.export(export_context, subdir) export_context.writeDataFile('.preserve', text='*', content_type='text/plain', subdir=subdir)
def _purgeUtilities(self): registrations = tuple(self.context.registeredUtilities()) blacklist = self._constructBlacklist() for registration in registrations: provided = registration.provided name = registration.name if _getDottedName(provided) in blacklist: continue self.context.unregisterUtility(provided=provided, name=name)
def extractInfoFromAssignment(name, assignment): klass = assignment.__class__ a = {'name' : name, 'class' : '%s' % _getDottedName(klass)} data = assignment.data kwargs = {} for i in list(providedBy(data)): if i.isOrExtends(IPortletDataProvider): for field_name, field in getFields(i).items(): kwargs[field_name] = field.get(assignment) a['kwargs'] = kwargs return a
def test_parseXML_normal_no_plugins(self): app, registry = self._initRegistry() importer = self._makeOne(registry).__of__(registry) reg_info = importer.parseXML(_NO_PLUGINS_PLUGINREGISTRY_EXPORT) self.assertEqual( len( reg_info['plugin_types'] ), 2 ) info = reg_info['plugin_types'][0] self.assertEqual(info['id'], 'IFoo') self.assertEqual(info['interface'], _getDottedName(IFoo)) self.assertEqual(info['title'], 'foo') self.assertEqual(info['description'], 'Some plugin interface') self.assertEqual(len( info['plugins'] ), 0) info = reg_info['plugin_types'][1] self.assertEqual(info['id'], 'IBar') self.assertEqual(info['interface'], _getDottedName(IBar)) self.assertEqual(info['title'], 'bar') self.assertEqual(info['description'], 'Another plugin interface') self.assertEqual(len( info['plugins'] ), 0 )
def _extractLayers(self): fragment = self._doc.createDocumentFragment() registrations = [r for r in self.context.registeredUtilities() if r.provided == ILocalBrowserLayerType] for r in registrations: child = self._doc.createElement("layer") child.setAttribute("name", r.name) child.setAttribute("interface", _getDottedName(r.component)) fragment.appendChild(child) return fragment
def _extractHandlers(self): fragment = self._doc.createDocumentFragment() registrations = [ {'factory': _getDottedName(reg.factory), 'required': reg.required} for reg in self.context.registeredHandlers() ] registrations.sort(key=itemgetter('factory')) registrations.sort(key=itemgetter('required')) for reg_info in registrations: child = self._doc.createElement('subscriber') for_ = u'' for interface in reg_info['required']: for_ = for_ + _getDottedName(interface) + u'\n ' child.setAttribute('handler', reg_info['factory']) child.setAttribute('for', for_.strip()) fragment.appendChild(child) return fragment
def _purgeSubscriptionAdapters(self): registrations = tuple(self.context.registeredSubscriptionAdapters()) blacklist = self._constructBlacklist() for registration in registrations: factory = registration.factory required = registration.required provided = registration.provided if _getDottedName(provided) in blacklist: continue self.context.unregisterSubscriptionAdapter(factory=factory, required=required, provided=provided)
def test_with_contents(self): from Products.GenericSetup.tests.common import DummyExportContext from Products.GenericSetup.tests.faux_objects \ import TestCSVAware from Products.GenericSetup.utils import _getDottedName from Products.PluggableAuthService.exportimport import exportPAS _setUpDefaultTraversable() self._setUpAdapters() app, pas = self._initPAS() csv_aware = TestCSVAware() csv_aware._setId('csv_plugin') pas._setObject('csv_plugin', csv_aware) context = DummyExportContext(pas) exportPAS(context) self.assertEqual(len(context._wrote), 4) filename, text, content_type = context._wrote[0] self.assertEqual(filename, 'PAS/.objects') self.assertEqual(content_type, 'text/comma-separated-values') objects = [x for x in reader(StringIO(text))] self.assertEqual(len(objects), 2) object_id, type_name = objects[0] self.assertEqual(object_id, 'plugins') self.assertEqual(type_name, 'plugins') # adapter-driven object_id, type_name = objects[1] self.assertEqual(object_id, 'csv_plugin') self.assertEqual(type_name, _getDottedName(csv_aware.__class__)) filename, text, content_type = context._wrote[1] self.assertEqual(filename, 'PAS/.properties') self.assertEqual(content_type, 'text/plain') lines = filter(None, [x.strip() for x in text.splitlines()]) lines = sorted(lines) self.assertEqual(len(lines), 3) self.assertEqual(lines[0], '[DEFAULT]') self.assertEqual(lines[1], 'login_transform =') self.assertEqual(lines[2], 'title =') filename, text, content_type = context._wrote[2] self.assertEqual(filename, 'PAS/pluginregistry.xml') self.assertEqual(content_type, 'text/xml') filename, text, content_type = context._wrote[3] self.assertEqual(filename, 'PAS/csv_plugin.csv') self.assertEqual(content_type, 'text/comma-separated-values')
def test_export_site_with_csvaware(self): from Products.GenericSetup.utils import _getDottedName self._setUpAdapters() site = _makeFolder('site') site.title = 'test_export_site_with_csvaware' site._setProperty('description', 'Testing export of an site with CSV-aware content.') aware = _makeCSVAware('aware') site._setObject('aware', aware) context = DummyExportContext(site) exporter = self._getExporter() exporter(context) self.assertEqual(len(context._wrote), 3) filename, text, content_type = context._wrote[0] self.assertEqual(filename, 'structure/.objects') self.assertEqual(content_type, 'text/comma-separated-values') objects = [x for x in reader(StringIO(text))] self.assertEqual(len(objects), 1) self.assertEqual(objects[0][0], 'aware') self.assertEqual(objects[0][1], _getDottedName(aware.__class__)) filename, text, content_type = context._wrote[1] self.assertEqual(filename, 'structure/.properties') self.assertEqual(content_type, 'text/plain') parser = ConfigParser() parser.readfp(StringIO(text)) defaults = parser.defaults() self.assertEqual(len(defaults), 2) self.assertEqual(defaults['title'], site.title) self.assertEqual(defaults['description'], site.description) filename, text, content_type = context._wrote[2] self.assertEqual(filename, 'structure/aware.csv') self.assertEqual(content_type, 'text/comma-separated-values') rows = [x for x in reader(StringIO(text))] self.assertEqual(len(rows), 2) self.assertEqual(rows[0][0], 'one') self.assertEqual(rows[0][1], 'two') self.assertEqual(rows[0][2], 'three') self.assertEqual(rows[1][0], 'four') self.assertEqual(rows[1][1], 'five') self.assertEqual(rows[1][2], 'six')
def test_with_contents(self): from Products.GenericSetup.tests.common import DummyExportContext from Products.GenericSetup.tests.faux_objects \ import TestCSVAware from Products.GenericSetup.utils import _getDottedName from Products.PluginRegistry.PluginRegistry import PluginRegistry from Products.PluggableAuthService.exportimport import exportPAS _setUpDefaultTraversable() self._setUpAdapters() app, pas = self._initPAS() csv_aware = TestCSVAware() csv_aware._setId('csv_plugin') pas._setObject('csv_plugin', csv_aware) context = DummyExportContext(pas) exportPAS(context) self.assertEqual(len(context._wrote), 4) filename, text, content_type = context._wrote[0] self.assertEqual(filename, 'PAS/.objects') self.assertEqual(content_type, 'text/comma-separated-values') objects = [x for x in reader(StringIO(text))] self.assertEqual(len(objects), 2) object_id, type_name = objects[0] self.assertEqual(object_id, 'plugins') self.assertEqual(type_name, 'plugins') # adapter-driven object_id, type_name = objects[1] self.assertEqual(object_id, 'csv_plugin') self.assertEqual(type_name, _getDottedName(csv_aware.__class__)) filename, text, content_type = context._wrote[1] self.assertEqual(filename, 'PAS/.properties') self.assertEqual(content_type, 'text/plain') lines = filter(None, [x.strip() for x in text.splitlines()]) self.assertEqual(len(lines), 2) self.assertEqual(lines[0], '[DEFAULT]') self.assertEqual(lines[1], 'title =') filename, text, content_type = context._wrote[2] self.assertEqual(filename, 'PAS/pluginregistry.xml') self.assertEqual(content_type, 'text/xml') filename, text, content_type = context._wrote[3] self.assertEqual(filename, 'PAS/csv_plugin.csv') self.assertEqual(content_type, 'text/comma-separated-values')
def test_parseXML_normal_with_plugins(self): app, registry = self._initRegistry() importer = self._makeOne(registry).__of__(registry) reg_info = importer.parseXML(_NORMAL_PLUGINREGISTRY_EXPORT) self.assertEqual(len(reg_info['plugin_types']), 2) info = reg_info['plugin_types'][0] self.assertEqual(info['id'], 'IFoo') self.assertEqual(info['interface'], _getDottedName(IFoo)) self.assertEqual(info['title'], 'foo') self.assertEqual(info['description'], 'Some plugin interface') plugins = info['plugins'] self.assertEqual(len(plugins), 2) self.assertEqual(plugins[0]['id'], 'foo_plugin_1') self.assertEqual(plugins[1]['id'], 'foo_plugin_2') info = reg_info['plugin_types'][1] self.assertEqual(info['id'], 'IBar') self.assertEqual(info['interface'], _getDottedName(IBar)) self.assertEqual(info['title'], 'bar') self.assertEqual(info['description'], 'Another plugin interface') self.assertEqual(len(info['plugins']), 0)
def _extractPortletNode(self, name, portletType): child = self._doc.createElement('portlet') child.setAttribute('addview', portletType.addview) child.setAttribute('title', portletType.title) child.setAttribute('description', portletType.description) for_ = portletType.for_ #BBB if for_ and for_ != [Interface]: for i in for_: subNode = self._doc.createElement('for') subNode.setAttribute('interface', _getDottedName(i)) child.appendChild(subNode) return child
def _extractPortletNode(self, name, portletType): child = self._doc.createElement("portlet") child.setAttribute("addview", portletType.addview) child.setAttribute("title", portletType.title) child.setAttribute("description", portletType.description) for_ = portletType.for_ # BBB if for_ and for_ != [Interface]: for i in for_: subNode = self._doc.createElement("for") subNode.setAttribute("interface", _getDottedName(i)) child.appendChild(subNode) return child
def _purgeAdapters(self): registrations = tuple(self.context.registeredAdapters()) blacklist = self._constructBlacklist() for registration in registrations: factory = registration.factory required = registration.required provided = registration.provided name = registration.name if _getDottedName(provided) in blacklist: continue self.context.unregisterAdapter(factory=factory, required=required, provided=provided, name=name)
def _extractPortletNode(self, name, portletType): child = self._doc.createElement('portlet') child.setAttribute('addview', portletType.addview) child.setAttribute('title', portletType.title) child.setAttribute('description', portletType.description) for_ = portletType.for_ #BBB # [Interface] is previous default value if for_ and for_ not in ([IDefaultPortletManager], [Interface]): for i in for_: subNode = self._doc.createElement('for') subNode.setAttribute('interface', _getDottedName(i)) child.appendChild(subNode) return child
def _extractLayers(self): fragment = self._doc.createDocumentFragment() registrations = [ r for r in self.context.registeredUtilities() if r.provided == ILocalBrowserLayerType ] registrations.sort() for r in registrations: child = self._doc.createElement('layer') child.setAttribute('name', r.name) child.setAttribute('interface', _getDottedName(r.component)) fragment.appendChild(child) return fragment
def test_export_site_with_exportable_simple_items(self): from Products.GenericSetup.tests.common import DummyExportContext from Products.GenericSetup.utils import _getDottedName self._setUpAdapters() ITEM_IDS = ('foo', 'bar', 'baz') site = _makeFolder('site') site.title = 'AAA' site._setProperty('description', 'CCC') aware = _makeINIAware('aside') dotted = _getDottedName(aware.__class__) for id in ITEM_IDS: site._setObject(id, _makeINIAware(id)) context = DummyExportContext(site) exporter = self._getExporter() exporter(context) self.assertEqual(len(context._wrote), 2 + len(ITEM_IDS)) filename, text, content_type = context._wrote[0] self.assertEqual(filename, 'structure/.objects') self.assertEqual(content_type, 'text/comma-separated-values') objects = _parseCSV(text) self.assertEqual(len(objects), 3) for index in range(len(ITEM_IDS)): self.assertEqual(objects[index][0], ITEM_IDS[index]) self.assertEqual(objects[index][1], dotted) filename, text, content_type = context._wrote[index+2] self.assertEqual(filename, 'structure/%s.ini' % ITEM_IDS[index]) object = site._getOb(ITEM_IDS[index]) self.assertEqual(text.strip(), object.as_ini().strip()) self.assertEqual(content_type, 'text/plain') filename, text, content_type = context._wrote[1] self.assertEqual(filename, 'structure/.properties') self.assertEqual(content_type, 'text/plain') parser = _parseINI(text) defaults = parser.defaults() self.assertEqual(len(defaults), 2) self.assertEqual(defaults['title'], 'AAA') self.assertEqual(defaults['description'], 'CCC')
def test_import_site_with_subitems_wo_adapter(self): from Products.GenericSetup.utils import _getDottedName item = _makeItem('no_adapter') dotted = _getDottedName(item.__class__) self._setUpAdapters() site = _makeFolder('site') context = DummyImportContext(site) # We want to add 'baz' to 'foo', without losing 'bar' context._files['structure/.objects'] = '\n'.join( ['%s,%s' % (x, dotted) for x in ('no_adapter', )]) importer = self._getImporter() importer(context) after = site.objectIds() self.assertEqual(len(after), 1) self.assertEqual(after[0], 'no_adapter')
def export(self, export_context, subdir, root=False): """ See IFilesystemExporter. """ context = self.context if not root: subdir = '%s/%s' % (subdir, context.getId()) exportable = self.listExportableItems() stream = StringIO() csv_writer = writer(stream) for object_id, object, adapter in exportable: factory_namer = IContentFactoryName(object, None) if factory_namer is None: factory_name = _getDottedName(object.__class__) else: factory_name = factory_namer() csv_writer.writerow((object_id, factory_name)) export_context.writeDataFile( '.objects', text=stream.getvalue(), content_type='text/comma-separated-values', subdir=subdir, ) prop_adapter = IINIAware(context, None) if prop_adapter is not None: export_context.writeDataFile( '.properties', text=prop_adapter.as_ini(), content_type='text/plain', subdir=subdir, ) for object_id, object, adapter in exportable: if adapter is not None: adapter.export(export_context, subdir)
def deriveSettingsFromSnapshots(self, before, after): actions = [a for a in (after['actions'] - before['actions'])] adapters = [] if len(after['adapters']) > len(before['adapters']): registrations = [reg for reg in after['adapters'] if reg not in before['adapters']] # TODO: expand this to actually cover adapter registrations utilities = [] if len(after['utilities']) > len(before['utilities']): registrations = [reg for reg in after['utilities'] if reg not in before['utilities']] for registration in registrations: reg = (_getDottedName(registration.provided), registration.name) utilities.append(reg) settings = dict( types=[t for t in after['types'] if t not in before['types']], skins=[s for s in after['skins'] if s not in before['skins']], actions=actions, workflows=[w for w in after['workflows'] if w not in before['workflows']], portalobjects=[a for a in after['portalobjects'] if a not in before['portalobjects']], leftslots=[s for s in after['leftslots'] if s not in before['leftslots']], rightslots=[s for s in after['rightslots'] if s not in before['rightslots']], adapters=adapters, utilities=utilities, registrypredicates=[s for s in after['registrypredicates'] if s not in before['registrypredicates']], ) jstool = getToolByName(self, 'portal_javascripts', None) if jstool is not None: settings['resources_js'] = [r for r in after['resources_js'] if r not in before['resources_js']] settings['resources_css'] = [r for r in after['resources_css'] if r not in before['resources_css']] return settings
def _modifyForList(self, node, for_): """Examine the "for_" nodes within a "portlet" node to populate, extend, and/or remove interface names from an existing list for_ """ modified_for = [_getDottedName(i) for i in for_] for subNode in node.childNodes: if subNode.nodeName.lower() == 'for': interface_name = str(subNode.getAttribute('interface')) if subNode.hasAttribute('remove'): if interface_name in modified_for: modified_for.remove(interface_name) elif interface_name not in modified_for: modified_for.append(interface_name) if node.hasAttribute("for"): raise InvalidPortletForDefinition(node) modified_for = [_resolveDottedName(name) for name in modified_for \ if _resolveDottedName(name) is not None] return modified_for
def registerStep( self, id, handler, title=None, description=None ): """ Register an export step. o 'id' is the unique identifier for this step o 'handler' is the dottoed name of a handler which should implement IImportPlugin. o 'title' is a one-line UI description for this step. If None, the first line of the documentation string of the step is used, or the id if no docstring can be found. o 'description' is a one-line UI description for this step. If None, the remaining line of the documentation string of the step is used, or default to ''. """ if not isinstance(handler, str): handler = _getDottedName( handler ) if title is None or description is None: method = _resolveDottedName(handler) if method is None: t,d = id, '' else: t, d = _extractDocstring( method, id, '' ) title = title or t description = description or d info = { 'id' : id , 'handler' : handler , 'title' : title , 'description' : description } self._registered[ id ] = info
def test_export_site_with_non_exportable_simple_items(self): from Products.GenericSetup.utils import _getDottedName self._setUpAdapters() ITEM_IDS = ('foo', 'bar', 'baz') site = _makeFolder('site') site.title = 'AAA' site._setProperty('description', 'BBB') item = _makeItem('aside') dotted = _getDottedName(item.__class__) for id in ITEM_IDS: site._setObject(id, _makeItem(id)) context = DummyExportContext(site) exporter = self._getExporter() exporter(context) self.assertEqual(len(context._wrote), 2) filename, text, content_type = context._wrote[0] self.assertEqual(filename, 'structure/.objects') self.assertEqual(content_type, 'text/comma-separated-values') objects = [x for x in reader(StringIO(text))] self.assertEqual(len(objects), 3) for index in range(len(ITEM_IDS)): self.assertEqual(objects[index][0], ITEM_IDS[index]) self.assertEqual(objects[index][1], dotted) filename, text, content_type = context._wrote[1] self.assertEqual(filename, 'structure/.properties') self.assertEqual(content_type, 'text/plain') parser = ConfigParser() parser.readfp(StringIO(text)) defaults = parser.defaults() self.assertEqual(len(defaults), 2) self.assertEqual(defaults['title'], 'AAA') self.assertEqual(defaults['description'], 'BBB')
def export(self, export_context, subdir, root=False): context = self.context if not root: subdir = '%s/%s' % (subdir, context.getId()) stream = BytesIO() csv_writer = writer(stream) exportable = self.listExportableItems() for object_id, obj, adapter_ in exportable: # noinspection PyUnresolvedReferences if hasattr(Acquisition.aq_base(obj), 'getPortalTypeName'): csv_writer.writerow((object_id, obj.getPortalTypeName())) else: factory_namer = IContentFactoryName(obj, None) if factory_namer is None: factory_name = _getDottedName(obj.__class__) else: factory_name = factory_namer() csv_writer.writerow((object_id, factory_name)) export_context.writeDataFile( '.objects', text=stream.getvalue(), content_type='text/comma-separated-values', # noqa subdir=subdir, ) prop_adapter = IINIAware(context, None) parser = ConfigParser() if prop_adapter is not None: parser.readfp(BytesIO(prop_adapter.as_ini())) title = context.Title() description = context.Description() title_str = encode_if_needed(title, 'utf-8') description_str = encode_if_needed(description, 'utf-8') parser.set('DEFAULT', 'Title', title_str) parser.set('DEFAULT', 'Description', description_str) stream = BytesIO() parser.write(stream) export_context.writeDataFile( '.properties', text=stream.getvalue(), content_type='text/plain', subdir=subdir, ) for object_id, obj, adapter_ in exportable: if adapter_ is not None: adapter_.export(export_context, subdir) export_context.writeDataFile('.preserve', text='*', content_type='text/plain', subdir=subdir)
def test__getDottedName_inst( self ): from Products.GenericSetup.utils import _getDottedName self.assertEqual( _getDottedName( whatever_inst ) , _WHATEVER_INST_NAME )
def test__getDottedName_class( self ): from Products.GenericSetup.utils import _getDottedName self.assertEqual( _getDottedName( Whatever ), _WHATEVER_NAME )
def test__getDottedName_string( self ): from Products.GenericSetup.utils import _getDottedName self.assertEqual( _getDottedName( _TEST_FUNC_NAME ), _TEST_FUNC_NAME )
def _extractPredictorNode(self, pred): """ """ child = self._doc.createElement('predictor') child.setAttribute('class', _getDottedName(pred.__class__)) child.setAttribute('name', pred.name()) return child
def _extractRules(self): """Extract rules to a document fragment """ site = self.environ.getSite() storage = queryUtility(IRuleStorage) if storage is None: return fragment = self._doc.createDocumentFragment() assignment_paths = set() for name, rule in storage.items(): rule_node = self._doc.createElement('rule') rule_node.setAttribute('name', name) rule_node.setAttribute('title', rule.title) rule_node.setAttribute('description', rule.description) rule_node.setAttribute('event', _getDottedName(rule.event)) rule_node.setAttribute('enabled', str(rule.enabled)) rule_node.setAttribute('stop-after', str(rule.stop)) rule_node.setAttribute('cascading', str(rule.cascading)) # Aq-wrap so that exporting fields with clever getters or # vocabularies will work. We also aq-wrap conditions and # actions below. rule = rule.__of__(site) # Add conditions conditions_node = self._doc.createElement('conditions') for condition in rule.conditions: condition_data = IRuleElementData(condition) condition = condition.__of__(rule) condition_node = self._doc.createElement('condition') condition_node.setAttribute('type', condition_data.element) handler = IRuleElementExportImportHandler(condition) handler.export_element(self._doc, condition_node) conditions_node.appendChild(condition_node) rule_node.appendChild(conditions_node) # Add actions actions_node = self._doc.createElement('actions') for action in rule.actions: action_data = IRuleElementData(action) action = action.__of__(rule) action_node = self._doc.createElement('action') action_node.setAttribute('type', action_data.element) handler = IRuleElementExportImportHandler(action) handler.export_element(self._doc, action_node) actions_node.appendChild(action_node) rule_node.appendChild(actions_node) fragment.appendChild(rule_node) assignment_paths.update(get_assignments(rule)) # Export assignments last - this is necessary to ensure they # are orderd properly site_path_length = len('/'.join(site.getPhysicalPath())) for path in assignment_paths: try: container = site.unrestrictedTraverse(path) except KeyError: continue assignable = IRuleAssignmentManager(container, None) if assignable is None: continue location = path[site_path_length:] for name, assignment in assignable.items(): assignment_node = self._doc.createElement('assignment') assignment_node.setAttribute('location', location) assignment_node.setAttribute('name', name) assignment_node.setAttribute('enabled', str(assignment.enabled)) assignment_node.setAttribute('bubbles', str(assignment.bubbles)) fragment.appendChild(assignment_node) return fragment
def listPluginTypes(self): for info in self.context.listPluginTypeInfo(): iface = info['interface'] info['interface'] = _getDottedName(iface) info['plugins'] = self.context.listPluginIds(iface) yield info
def registerStep( self , id , version=None , handler=None , dependencies=() , title=None , description=None ): """ Register a setup step. o 'id' is a unique name for this step, o 'version' is a string for comparing versions, it is preferred to be a yyyy/mm/dd-ii formatted string (date plus two-digit ordinal). when comparing two version strings, the version with the lower sort order is considered the older version. - Newer versions of a step supplant older ones. - Attempting to register an older one after a newer one results in a KeyError. o 'handler' is the dottoed name of a handler which should implement IImportPlugin. o 'dependencies' is a tuple of step ids which have to run before this step in order to be able to run at all. Registration of steps that have unmet dependencies are deferred until the dependencies have been registered. o 'title' is a one-line UI description for this step. If None, the first line of the documentation string of the handler is used, or the id if no docstring can be found. o 'description' is a one-line UI description for this step. If None, the remaining line of the documentation string of the handler is used, or default to ''. """ already = self.getStepMetadata( id ) if handler is None: raise ValueError, 'No handler specified' if already and already[ 'version' ] > version: raise KeyError( 'Existing registration for step %s, version %s' % ( id, already[ 'version' ] ) ) if not isinstance(handler, str): handler = _getDottedName( handler ) if title is None or description is None: method = _resolveDottedName(handler) if method is None: t,d = id, '' else: t, d = _extractDocstring( method, id, '' ) title = title or t description = description or d info = { 'id' : id , 'version' : version , 'handler' : handler , 'dependencies' : dependencies , 'title' : title , 'description' : description } self._registered[ id ] = info
from zope.component import queryMultiAdapter from zope.component.interfaces import ComponentLookupError from zope.component.interfaces import IComponentRegistry from zope.location.interfaces import IPossibleSite from Acquisition import aq_base from Acquisition import aq_parent from Products.GenericSetup.interfaces import IBody from Products.GenericSetup.interfaces import IComponentsHandlerBlacklist from Products.GenericSetup.interfaces import ISetupEnviron from Products.GenericSetup.utils import XMLAdapterBase from Products.GenericSetup.utils import _getDottedName from Products.GenericSetup.utils import _resolveDottedName BLACKLIST_SELF = _getDottedName(IComponentsHandlerBlacklist) class ComponentRegistryXMLAdapter(XMLAdapterBase): """XML im- and exporter for a local component registry. """ adapts(IComponentRegistry, ISetupEnviron) _LOGGER_ID = 'componentregistry' name = 'componentregistry' def _constructBlacklist(self): blacklist = set((BLACKLIST_SELF, )) utils = getUtilitiesFor(IComponentsHandlerBlacklist)
def testRegisteredInterfaces(self): portlet = getUtility(IPortletType, name='portlets.Navigation') registered_interfaces = [_getDottedName(i) for i in portlet.for_] registered_interfaces.sort() self.assertEqual(['plone.app.portlets.interfaces.IColumn'], registered_interfaces)
def testRegisteredInterfaces(self): portlet = getUtility(IPortletType, name=u'edrnsite.portlets.QuickLinks') registeredInterfaces = [_getDottedName(i) for i in portlet.for_] registeredInterfaces.sort() self.assertEquals(['plone.app.portlets.interfaces.IColumn', 'plone.app.portlets.interfaces.IDashboard'], registeredInterfaces)
<?xml version="1.0"?> <plugin-registry> <plugin-type id="IFoo" interface="%s" title="foo" description="Some plugin interface"> </plugin-type> <plugin-type id="IBar" interface="%s" title="bar" description="Another plugin interface"> </plugin-type> </plugin-registry> """ % (_getDottedName(IFoo), _getDottedName(IBar)) _NORMAL_PLUGINREGISTRY_EXPORT = """\ <?xml version="1.0"?> <plugin-registry> <plugin-type id="IFoo" interface="%s" title="foo" description="Some plugin interface"> <plugin id="foo_plugin_1" /> <plugin id="foo_plugin_2" /> </plugin-type> <plugin-type id="IBar" interface="%s"
def getExcludedInterfaces(self): return ( _getDottedName(IPortletType), _getDottedName(IPortletManager), _getDottedName(IPortletManagerRenderer), )