def evolve(context): root = getRootFolder(context) site = None for s in findObjectsProviding(root, IQuotationtoolSite): site = s break if site is None: raise Exception('No quotationtool site') hooks.setSite(site) sm = site.getSiteManager() # a container for unified comments was added container = site['comments'] = CommentContainer() sm.registerUtility(container, ICommentContainer) IWriteZopeDublinCore(container).title = u"Comments" IWriteZopeDublinCore( container).description = u"""Comments are stored here.""" # relation catalog has changed because of unified comments cat = zope.component.getUtility(zc.relation.interfaces.ICatalog, context=site) cat.removeValueIndex('icommentaboutfigure-figure') cat.removeValueIndex('icommentaboutreference-reference') cat.addValueIndex(IComment['about'], dump=dump, load=load, name='icomment-about')
def setUpFieldConfig(test): test.globs = {'root': placefulSetUp(True)} # placeful setup root = test.globs['root'] setUpZCML(test) hooks.setSite(root) interaction = newInteraction() testing.generateCategorizableItemDescriptions(root)
def evolve(context): """ Add a commentary folder and its relation catalog.""" root = getRootFolder(context) site = None for s in findObjectsProviding(root, IQuotationtoolSite): site = s break if site is None: raise Exception('No quotationtool site') hooks.setSite(site) sm = site.getSiteManager() container = site['aboutreferences'] = CommentAboutReferenceContainer() sm.registerUtility(container, ICommentAboutReferenceContainer) IWriteZopeDublinCore(container).title = u"Comments about References" IWriteZopeDublinCore( container ).description = u"""Comments about references in the referatory are stored here.""" cat = sm['default'][ 'commentaboutreference_relation_catalog'] = zc.relation.catalog.Catalog( dump, load) cat.addValueIndex(ICommentAboutReference['reference'], dump, load) sm.registerUtility(cat, zc.relation.interfaces.ICatalog, name='commentsaboutreferences')
def addConfiguredSite(dispatcher, site_id, profile_id, snapshot=True, RESPONSE=None, extension_ids=()): """ Add a CMFSite to 'dispatcher', configured according to 'profile_id'. """ site = CMFSite(site_id) dispatcher._setObject(site_id, site) site = dispatcher._getOb(site_id) setSite(site) site._setObject(_TOOL_ID, SetupTool(_TOOL_ID)) setup_tool = getToolByName(site, _TOOL_ID) setup_tool.setBaselineContext('profile-%s' % profile_id) setup_tool.runAllImportStepsFromProfile('profile-%s' % profile_id) for extension_id in extension_ids: setup_tool.runAllImportStepsFromProfile('profile-%s' % extension_id) if snapshot is True: setup_tool.createSnapshot('initial_configuration') if RESPONSE is not None: RESPONSE.redirect('%s/%s/manage_main?update_menu=1' % (dispatcher.absolute_url(), site_id))
def test_components_unregistered_on_delete(self): portal_type = u"testtype" fti = DexterityFTI(portal_type) container_dummy = self.create_dummy() # Mock the lookup of the site and the site manager at the site root dummy_site = self.create_dummy() self.mock_utility(dummy_site, ISiteRoot) site_manager_mock = self.mocker.proxy(PersistentComponents(bases=(getGlobalSiteManager(),))) getSiteManager_mock = self.mocker.replace('zope.app.component.hooks.getSiteManager') self.expect(getSiteManager_mock(dummy_site)).result(site_manager_mock).count(1,None) # We expect to always be able to unregister without error, even if the # components do not exists (as here) self.expect(site_manager_mock.unregisterUtility(provided=IDexterityFTI, name=portal_type)).passthrough() self.expect(site_manager_mock.unregisterUtility(provided=IFactory, name=portal_type)).passthrough() self.replay() # First add the components ftiAdded(fti, ObjectAddedEvent(fti, container_dummy, fti.getId())) # Then remove them again ftiRemoved(fti, ObjectRemovedEvent(fti, container_dummy, fti.getId())) site_dummy = self.create_dummy(getSiteManager = lambda: site_manager_mock) setSite(site_dummy) setHooks() self.assertEquals(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertEquals(None, queryUtility(IFactory, name=portal_type))
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # space space = ContentSpace(title=u'Space') event.notify(ObjectCreatedEvent(space)) root['space'] = space # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) endInteraction()
def test_traversing(self): site = self.stub() self.expect(site.getSiteManager()).call(getGlobalSiteManager) self.expect(site.absolute_url()).result('http://nohost/plone') request = self.create_dummy( form={'ori': 'formdata'}, RESPONSE=self.create_dummy( headers={})) self.expect(site.REQUEST).result(request) assertion_data = self.create_dummy() def view_method(): assertion_data.form = request.form.copy() return 'the url %s@@view should be replaced' % ( PORTAL_URL_PLACEHOLDER) with self.mocker.order(): # test 1 self.expect(site.restrictedTraverse('baz/@@view')()).call( view_method) # test 2 self.expect(site.restrictedTraverse('baz/@@view')()).throw( Exception('failed')) # test 3 self.expect(site.restrictedTraverse('baz/@@view')()).throw( ConflictError()) self.replay() utility = getUtility(IBridgeRequest) setSite(site) # test 1 response = utility( 'current-client', 'baz/@@view?foo=bar&baz=%s' % PORTAL_URL_PLACEHOLDER, data={'url': PORTAL_URL_PLACEHOLDER}) self.assertEqual(assertion_data.form, { 'foo': 'bar', 'url': 'http://nohost/plone/', 'baz': 'http://nohost/plone/'}) self.assertEqual(request.form, {'ori': 'formdata'}) self.assertEqual(response.code, 200) self.assertEqual( response.read(), 'the url http://nohost/plone/@@view should be replaced') # test 2 with self.assertRaises(urllib2.HTTPError) as cm: response = utility('current-client', 'baz/@@view?foo=bar') response = cm.exception self.assertEqual(request.form, {'ori': 'formdata'}) self.assertEqual(response.code, 500) self.assertIn(response.read(), 'failed') # test 3 with self.assertRaises(ConflictError): utility('current-client', 'baz/@@view?foo=bar')
def __init__(self): self.instancehome = os.environ.get("INSTANCE_HOME") configfile = os.environ.get("CONFIG_FILE") if configfile is None and self.instancehome is not None: configfile = os.path.join(self.instancehome, "etc", "zope.conf") if configfile is None: raise RuntimeError("CONFIG_FILE env not set") print "CONFIG_FILE=", configfile print "INSTANCE_HOME=", self.instancehome self.configfile = configfile try: from Zope2 import configure except ImportError: from Zope import configure configure(configfile) try: import Zope2 app = Zope2.app() except ImportError: import Zope app = Zope.app() from Testing.makerequest import makerequest self.app = makerequest(app) try: self._make_permissive() print "Permissive security installed" except: print "Permissive security NOT installed" self._pwd = self.portal or self.app try: from zope.component import getSiteManager from zope.component import getGlobalSiteManager try: from zope.app.component.hooks import setSite except ImportError: from zope.component.hooks import setSite if self.portal is not None: setSite(self.portal) gsm = getGlobalSiteManager() sm = getSiteManager() if sm is gsm: print "ERROR SETTING SITE!" except: # XXX: What exceptions is this supposed to catch? pass
def create_image_mocks(self, image_layout, caption, uid, floated=True): context, request, layout = self.get_mocks() self.site = self.create_dummy(REQUEST=request, getSiteManager=getSiteManager) setSite(self.site) image = self.create_dummy(get_size=lambda: 11, data='hello world') builder = self.mocker.mock() self.expect(layout.get_builder()).result(builder) self.expect(builder.add_file('%s_image.jpg' % uid, image.data)) self.expect(layout.use_package('graphicx')) if floated: self.expect(layout.use_package('wrapfig')) self.expect(layout.use_package('checkheight')) self.expect(layout.get_builder()).result(builder) self.expect(builder.add_file('checkheight.sty', ANY)) self.expect(builder.build_directory).result('/tmp') self.expect(context.getImage()).result(image).count(1, None) self.expect(context.image_layout).result(image_layout) self.expect(context.getImageCaption()).result(caption) self.expect(context.UID()).result(uid) return context, request, layout
def test_global_components_not_unregistered_on_delete(self): portal_type = u"testtype" fti = DexterityFTI(portal_type) container_dummy = self.create_dummy() # Mock the lookup of the site and the site manager at the site root dummy_site = self.create_dummy() self.mock_utility(dummy_site, ISiteRoot) site_manager_mock = self.mocker.proxy(PersistentComponents(bases=(getGlobalSiteManager(),))) getSiteManager_mock = self.mocker.replace('zope.app.component.hooks.getSiteManager') self.expect(getSiteManager_mock(dummy_site)).result(site_manager_mock) # Register FTI utility and factory utility self.mock_utility(fti, IDexterityFTI, name=portal_type) self.mock_utility(DexterityFactory(portal_type), IFactory, name=portal_type) # We expect to always be able to unregister without error, even if the # component exists. The factory is only unregistered if it was registered # with info='plone.dexterity.dynamic'. self.expect(site_manager_mock.unregisterUtility(provided=IDexterityFTI, name=portal_type)).passthrough() self.replay() ftiRemoved(fti, ObjectRemovedEvent(fti, container_dummy, fti.getId())) site_dummy = self.create_dummy(getSiteManager = lambda: site_manager_mock) setSite(site_dummy) setHooks() self.assertNotEquals(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertNotEquals(None, queryUtility(IFactory, name=portal_type))
def test_getNextUtility(self): # test local site vs. global site global_dummy = DummyUtility() provideUtility(global_dummy, IDummyUtility) local_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, local_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy) # test local site vs. nested local site manage_addDummySite(self.folder.site, 'subsite') enableLocalSiteHook(self.folder.site.subsite) setSite(self.folder.site.subsite) sublocal_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, sublocal_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), sublocal_dummy) self.assertEquals(getNextUtility(self.folder.site.subsite, IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy)
def test_nestedSitesDontConflictButStillAcquire(self): # let's register a dummy utility in the dummy site dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, dummy) # let's also create a subsite and make that our site manage_addDummySite(self.folder.site, 'subsite') enableLocalSiteHook(self.folder.site.subsite) setSite(self.folder.site.subsite) # we should still be able to lookup the original utility from # the site one level above self.assertEqual(zapi.getUtility(IDummyUtility), dummy) # now we register a dummy utility in the subsite and see that # its registration doesn't conflict subdummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, subdummy) # when we look it up we get the more local one now because the # more local one shadows the less local one self.assertEqual(zapi.getUtility(IDummyUtility), subdummy) # getAllUtilitiesFor gives us both the more local and the less # local utility (XXX not sure if this is the right semantics # for getAllUtilitiesFor) self.assertEqual(sets.Set(zapi.getAllUtilitiesRegisteredFor(IDummyUtility)), sets.Set([subdummy, dummy])) # getUtilitiesFor will only find one, because the more local # one shadows the less local one self.assertEqual(list(zapi.getUtilitiesFor(IDummyUtility)), [('', subdummy)])
def setUp(self): super(AttributionTests, self).setUp() self.root = placefulSetUp(True) setUpZCML(self) hooks.setSite(self.root) # we need a transaction from zope.security.management import newInteraction interaction = newInteraction() testing.generateCategorizableItemDescriptions(self.root) testing.generateCategoriesContainer(self.root) testing.setUpIntIds(self) testing.setUpIndices(self) testing.setUpRelationCatalog(self) from quotationtool.workflow import testing as workflowtesting workflowtesting.setUpWorkLists(self.root) workflowtesting.setUpIndices(self) from quotationtool.workflow.interfaces import IWorkList self.editor_items = zope.component.getUtility(IWorkList, name='editor', context=self.root) self.contributor_items = zope.component.getUtility(IWorkList, name='contributor', context=self.root) # create item and its intid from quotationtool.workflow.interfaces import IHasWorkflowHistory zope.interface.classImplements(testing.Categorizable, IHasWorkflowHistory) self.root['item'] = item = testing.Categorizable() from zope.intid.interfaces import IIntIds self.intids = zope.component.getUtility(IIntIds, context=self.root) self.intids.register(self.root['item'])
def setUp(test): functional.FunctionalTestSetup().setUp() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # people root['people'] = PersonalSpaceManager() sm.registerUtility(root['people'], IPersonalSpaceManager) user = sm.getUtility(IAuthentication).getPrincipal('zope.mgr') root['people'].assignPersonalSpace(user) user = sm.getUtility(IAuthentication).getPrincipal('zope.user1') root['people'].assignPersonalSpace(user) user = sm.getUtility(IAuthentication).getPrincipal('zope.user2') root['people'].assignPersonalSpace(user)
def setUp(self): super(SearchTests, self).setUp() self.root = placefulSetUp(True) setUpZCML(self) import quotationtool.search XMLConfig('configure.zcml', quotationtool.search)() hooks.setSite(self.root) # we need a transaction from zope.security.management import newInteraction interaction = newInteraction() testing.generateCategorizableItemDescriptions(self.root) testing.generateCategoriesContainer(self.root) testing.setUpIntIds(self) testing.setUpIndices(self) testing.setUpRelationCatalog(self) self.root['item1'] = item1 = testing.Categorizable() self.root['item2'] = item2 = testing.Categorizable() from zope.intid.interfaces import IIntIds self.intids = zope.component.getUtility(IIntIds, context=self.root) self.intids.register(self.root['item1']) self.intids.register(self.root['item2']) attribution1 = interfaces.IAttribution(item1) attribution1.set(('cat11', 'cat21', 'cat31',)) attribution2 = interfaces.IAttribution(item2) attribution2.set(('cat12', 'cat22', 'cat32',)) from quotationtool.search.searcher import QuotationtoolSearchFilter zope.interface.classImplements( QuotationtoolSearchFilter, interfaces.IAttributionSearchFilter)
def test_components_reregistered_on_rename(self): portal_type = u"testtype" fti = DexterityFTI(portal_type) container_dummy = self.create_dummy() # Mock the lookup of the site and the site manager at the site root dummy_site = self.create_dummy() self.mock_utility(dummy_site, ISiteRoot) site_manager_mock = self.mocker.proxy(PersistentComponents(bases=(getGlobalSiteManager(),))) getSiteManager_mock = self.mocker.replace('zope.app.component.hooks.getSiteManager') self.expect(getSiteManager_mock(dummy_site)).result(site_manager_mock).count(1,None) # First look for unregistration of all local components self.expect(site_manager_mock.unregisterUtility(provided=IDexterityFTI, name=portal_type)).passthrough() # Then look for re-registration of global components self.expect(site_manager_mock.registerUtility(fti, IDexterityFTI, portal_type, info='plone.dexterity.dynamic')).passthrough() self.expect(site_manager_mock.registerUtility( mocker.MATCH(lambda x: isinstance(x, DexterityFactory) and x.portal_type == portal_type), IFactory, portal_type, info='plone.dexterity.dynamic')).passthrough() self.assertEquals('string:${folder_url}/++add++testtype', fti.add_view_expr) self.replay() ftiRenamed(fti, ObjectMovedEvent(fti, container_dummy, fti.getId(), container_dummy, u"newtype")) site_dummy = self.create_dummy(getSiteManager = lambda: site_manager_mock) setSite(site_dummy) setHooks() self.assertNotEquals(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertNotEquals(None, queryUtility(IFactory, name=portal_type))
def test_traversing(self): site = self.stub() self.expect(site.getSiteManager()).call(getGlobalSiteManager) self.expect(site.absolute_url()).result('http://nohost/plone') request = self.create_dummy(form={'ori': 'formdata'}, RESPONSE=self.create_dummy(headers={})) self.expect(site.REQUEST).result(request) assertion_data = self.create_dummy() def view_method(): assertion_data.form = request.form.copy() return 'the url %s@@view should be replaced' % ( PORTAL_URL_PLACEHOLDER) with self.mocker.order(): # test 1 self.expect( site.restrictedTraverse('baz/@@view')()).call(view_method) # test 2 self.expect(site.restrictedTraverse('baz/@@view')()).throw( Exception('failed')) # test 3 self.expect(site.restrictedTraverse('baz/@@view')()).throw( ConflictError()) self.replay() utility = getUtility(IBridgeRequest) setSite(site) # test 1 response = utility('current-client', 'baz/@@view?foo=bar&baz=%s' % PORTAL_URL_PLACEHOLDER, data={'url': PORTAL_URL_PLACEHOLDER}) self.assertEqual( assertion_data.form, { 'foo': 'bar', 'url': 'http://nohost/plone/', 'baz': 'http://nohost/plone/' }) self.assertEqual(request.form, {'ori': 'formdata'}) self.assertEqual(response.code, 200) self.assertEqual( response.read(), 'the url http://nohost/plone/@@view should be replaced') # test 2 with self.assertRaises(urllib2.HTTPError) as cm: response = utility('current-client', 'baz/@@view?foo=bar') response = cm.exception self.assertEqual(request.form, {'ori': 'formdata'}) self.assertEqual(response.code, 500) self.assertIn(response.read(), 'failed') # test 3 with self.assertRaises(ConflictError): utility('current-client', 'baz/@@view?foo=bar')
def run(self, forever=True): atexit.register(self.stop) while not self.__stopped: if LinuxHaConnectionThread.database: try: conn = LinuxHaConnectionThread.database.open() root = conn.root() root_folder = root['Application'] old_site = getSite() setSite(root_folder) myAdmUtilLinuxHa = queryUtility(IAdmUtilLinuxHa) if myAdmUtilLinuxHa is not None: utilOId = myAdmUtilLinuxHa.getObjectId() if myAdmUtilLinuxHa.LinuxHaServerActive: self.executeMyQueue(myAdmUtilLinuxHa) else: if not self.getQueue(utilOId)['in'].empty(): self.getQueue(utilOId)['in'].get(True, 5) self.getQueue(utilOId)['in'].task_done() transaction.commit() conn.close() # Blanket except because we don't want # this thread to ever die except Exception, err: logger.error("Error in ESX VIM (%s)" % err, exc_info=True) transaction.abort() conn.close() #-------------------------------------------------------------------------------- if forever: time.sleep(0.01) else: break
def bootstrapSubscriber(ev): db, connection, root, portal = getInformationFromEvent(ev) if portal is None: portal = Portal(title=u'Portal') interface.alsoProvides(portal, IContainmentRoot) event.notify(ObjectCreatedEvent(portal)) root[ZopePublication.root_name] = portal transaction.commit() try: reconfigurePortal(portal) setSite(portal) catalog = component.getUtility(IConfiglet, 'system.catalog').catalog catalog.clear() catalog.updateIndexes() setSite(None) except: del root[ZopePublication.root_name] transaction.commit() raise transaction.commit() connection.close() event.notify(DatabaseOpenedWithRoot(db))
def setUp(test): functional.FunctionalTestSetup().setUp() root = functional.getRootFolder() setSite(root) setUpCache() sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # people root['people'] = PersonalSpaceManager() sm.registerUtility(root['people'], IPersonalSpaceManager) # space space = ContentSpace(title=u'Space') event.notify(ObjectCreatedEvent(space)) root['space'] = space interface.directlyProvides(root['space'], IDoNotCacheActionsPortlet)
def evolve(context): root = getRootFolder(context) site = None for s in findObjectsProviding(root, IQuotationtoolSite): site = s break if site is None: raise Exception('No quotationtool site') hooks.setSite(site) sm = site.getSiteManager() # a container for unified comments was added categorizable_items = site[ 'categorizableitems'] = CategorizableItemDescriptions() sm.registerUtility(categorizable_items, ICategorizableItemDescriptions) IWriteZopeDublinCore( categorizable_items).title = u"Categorizable Item Descriptions" IWriteZopeDublinCore( categorizable_items ).description = u"""Mapping of ZOPE-Interfaces to user friendly identifiers.""" categories = site['categories'] = CategoriesContainer() sm.registerUtility(categories, ICategoriesContainer) IWriteZopeDublinCore(categorizable_items).title = u"Categories" IWriteZopeDublinCore( categorizable_items ).description = u"""User defined categories for classifying user content."""
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() sm.getUtility(INameChooserConfiglet).short_url_enabled = True # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) setattr(root, 'principalId', 'zope.mgr') # space space = ContentSpace(title=u'Space') event.notify(ObjectCreatedEvent(space)) root['space'] = space setattr(root, 'principal', getUtility(IAuthentication).getPrincipal('zope.mgr')) # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) endInteraction()
def setUp(test): functional.FunctionalTestSetup().setUp() root = functional.getRootFolder() setSite(root) # IIntIds root['ids'] = IntIds() root.getSiteManager().registerUtility(root['ids'], IIntIds) # catalog root['catalog'] = Catalog() root.getSiteManager().registerUtility(root['catalog'], ICatalog) # default content content = Content1('Content 1') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content11'] = content content = Content1('Content 2') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content12'] = content content = Content2('Content 3') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content21'] = content content = Content2('Content 4') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content22'] = content
def setUp(test): functional.FunctionalTestSetup().setUp() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # personal space manager root['people'] = PersonalSpaceManager() sm.registerUtility(root['people'], IPersonalSpaceManager) # default content content = Content() event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content'] = content
def harvest(): db = component.getUtility(IDatabase) conn = db.open() root = conn.root().data['Application'] portal = IPortal(root, None) if portal is None: # Old instance of zojax where portal is not the root object. # We get the first instance of IPortal if it exists. for obj in root.values(): portal = IPortal(obj, None) if portal is not None: break if portal is None: conn.close() return setSite(portal) catalog = component.getUtility(ICatalogConfiglet, context=portal).catalog workspaces = catalog.searchResults(type={'any_of': ('contenttype.rss.workspace',)}) try: for workspace in workspaces: if workspace.harvest(): transaction.commit() else: transaction.abort() except: transaction.abort() conn.close()
def test_components_registered_on_add(self): portal_type = u"testtype" fti = DexterityFTI(portal_type) container_dummy = self.create_dummy() # Mock the lookup of the site and the site manager at the site root dummy_site = self.create_dummy() self.mock_utility(dummy_site, ISiteRoot) site_manager_mock = self.mocker.proxy(PersistentComponents(bases=(getGlobalSiteManager(),))) getSiteManager_mock = self.mocker.replace('zope.app.component.hooks.getSiteManager') self.expect(getSiteManager_mock(dummy_site)).result(site_manager_mock) # We expect that no components are registered , so look for all registrations self.expect(site_manager_mock.registerUtility(fti, IDexterityFTI, portal_type, info='plone.dexterity.dynamic')).passthrough() self.expect(site_manager_mock.registerUtility( mocker.MATCH(lambda x: isinstance(x, DexterityFactory) and x.portal_type == portal_type), IFactory, portal_type, info='plone.dexterity.dynamic')).passthrough() self.replay() ftiAdded(fti, ObjectAddedEvent(fti, container_dummy, fti.getId())) site_dummy = self.create_dummy(getSiteManager = lambda: site_manager_mock) setSite(site_dummy) setHooks() self.assertNotEquals(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertNotEquals(None, queryUtility(IFactory, name=portal_type))
def importit(app): site = app[SITE_ID] setSite(site) per_folder = 50 num_folders = 7 max_depth = 4 portal_types = ['Document', 'News Item', 'Event'] data = Data() def populate(parent, count=0, depth=0): if depth >= max_depth: return count for fidx in range(num_folders): count += 1 folder = createObject(parent, 'Folder', 'folder%i' % fidx, check_for_first=True, delete_first=False, title="Folder %i" % fidx) for didx in range(per_folder): count += 1 print 'created ', count createObject(folder, random.choice(portal_types), 'page%i' % didx, check_for_first=True, delete_first=False, title="Page %i" % didx, text=data.next()) count = populate(folder, count, depth + 1) print 'commiting' transaction.commit() app._p_jar.cacheMinimize() return count populate(site)
def create_image_mocks(self, image_layout, caption, uid, floated=True): context, request, layout = self.get_mocks() self.site = self.create_dummy( REQUEST=request, getSiteManager=getSiteManager) setSite(self.site) image = self.create_dummy(get_size=lambda: 11, data='hello world') builder = self.mocker.mock() self.expect(layout.get_builder()).result(builder) self.expect(builder.add_file('%s_image.jpg' % uid, image.data)) self.expect(layout.use_package('graphicx')) if floated: self.expect(layout.use_package('wrapfig')) self.expect(layout.use_package('checkheight')) self.expect(layout.get_builder()).result(builder) self.expect(builder.add_file('checkheight.sty', ANY)) self.expect(builder.build_directory).result('/tmp') self.expect(context.getImage()).result(image).count(1, None) self.expect(context.image_layout).result(image_layout) self.expect(context.getImageCaption()).result(caption) self.expect(context.UID()).result(uid) return context, request, layout
def test_getServices(self): self.assertEqual(getServices_hook(None), serviceManager) self.assertEqual(getServices_hook(self.root), serviceManager) self.assertEqual(getServices_hook(self.f1), self.sm1) self.assertEqual(getServices_hook(self.f2), self.sm2) setSite(self.f2) self.assertEqual(getServices_hook(None), self.sm2)
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # setup default role roles = sm.getUtility(IPortalRoles) if 'site.member' not in roles: role = PortalRole(title = u'Site Member') event.notify(ObjectCreatedEvent(role)) roles['site.member'] = role roleId = role.id sm.getUtility(IDefaultPortalRole).roles = [role.id] endInteraction()
def setUp(test): functional.FunctionalTestSetup().setUp() root = functional.getRootFolder() setSite(root) setUpCache() sm = root.getSiteManager() # IIntIds root['ids'] = IntIds() sm.registerUtility(root['ids'], IIntIds) root['ids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # people root['people'] = PersonalSpaceManager() sm.registerUtility(root['people'], IPersonalSpaceManager) user = sm.getUtility(IAuthentication).getPrincipal('zope.mgr') root['people'].assignPersonalSpace(user) activity = sm.getUtility(IActivity) try: activity.remove(activity.records.keys()[0]) except IndexError: pass
def threadSiteSubscriber(event): """A subscriber to BeforeTraverseEvent Sets the 'site' thread global if the object traversed is a site. """ if interfaces.ISite.providedBy(event.object): setSite(event.object)
def addConfiguredSite(dispatcher, site_id, profile_id, snapshot=True, RESPONSE=None, extension_ids=()): """ Add a CMFSite to 'dispatcher', configured according to 'profile_id'. """ site = CMFSite( site_id ) dispatcher._setObject( site_id, site ) site = dispatcher._getOb( site_id ) setSite(site) site._setObject(_TOOL_ID, SetupTool(_TOOL_ID)) setup_tool = getattr(site, _TOOL_ID) setup_tool.setImportContext( 'profile-%s' % profile_id ) setup_tool.runAllImportSteps() for extension_id in extension_ids: setup_tool.setImportContext( 'profile-%s' % extension_id ) setup_tool.runAllImportSteps() setup_tool.setImportContext( 'profile-%s' % profile_id ) if snapshot is True: setup_tool.createSnapshot( 'initial_configuration' ) if RESPONSE is not None: RESPONSE.redirect( '%s/%s/manage_main?update_menu=1' % (dispatcher.absolute_url(), site_id) )
def afterSetUp(self): setSite(self.app.site) newSecurityManager(None, UnrestrictedUser('god', '', ['Manager'], '')) # sessioning setup sdm = self.app.session_data_manager self.app.REQUEST.set_lazy('SESSION', sdm.getSessionData)
def test_getNextUtility(self): # test local site vs. global site global_dummy = DummyUtility() provideUtility(global_dummy, IDummyUtility) local_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, local_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy) # test local site vs. nested local site manage_addDummySite(self.folder.site, 'subsite') enableLocalSiteHook(self.folder.site.subsite) setSite(self.folder.site.subsite) sublocal_dummy = DummyUtility() sm = zapi.getSiteManager() sm.registerUtility(IDummyUtility, sublocal_dummy) self.assertEquals(zapi.getUtility(IDummyUtility), sublocal_dummy) self.assertEquals( getNextUtility(self.folder.site.subsite, IDummyUtility), local_dummy) self.assertEquals(getNextUtility(self.folder.site, IDummyUtility), global_dummy)
def cbFun(self, transportDispatcher, transportDomain, transportAddress, wholeMsg): """ this callback function which will handle the snmptrap message from pysnmp stack """ while wholeMsg: msgVer = int(api.decodeMessageVersion(wholeMsg)) if api.protoModules.has_key(msgVer): pMod = api.protoModules[msgVer] else: print 'Unsupported SNMP version %s' % msgVer return reqMsg, wholeMsg = decoder.decode( wholeMsg, asn1Spec=pMod.Message(), ) print 'Notification message from %s:%s: ' % ( transportDomain, transportAddress ) reqPDU = pMod.apiMessage.getPDU(reqMsg) if reqPDU.isSameTypeWith(pMod.TrapPDU()): if SnmpdThread.database: conn = SnmpdThread.database.open() root = conn.root() root_folder = root['Application'] old_site = getSite() setSite(root_folder) my_catalog = zapi.getUtility(ICatalog) search_ip = pMod.apiTrapPDU.getAgentAddr(reqPDU).prettyPrint() search_ip_conv = convertIpV4(search_ip) for result in my_catalog.searchResults(\ interface_ip_index=search_ip_conv): parentObj = result.__parent__ snmpAdapter = ISnmptrapd(parentObj) snmpAdapter.triggered(reqPDU, msgVer, pMod) setSite(old_site) transaction.commit() conn.close() return wholeMsg
def wrapped_func(*args, **kw): sm, site = getSecurityManager(), getSite() try: return func(*args, **kw) finally: setSecurityManager(sm) setSite(site)
def test_removeIntIdSubscriber(self): from zope.app.intid import removeIntIdSubscriber from zope.app.container.contained import ObjectRemovedEvent from zope.app.intid.interfaces import IIntIdRemovedEvent parent_folder = self.root['folder1']['folder1_1'] folder = self.root['folder1']['folder1_1']['folder1_1_1'] id = self.utility.register(folder) id1 = self.utility1.register(folder) self.assertEquals(self.utility.getObject(id), folder) self.assertEquals(self.utility1.getObject(id1), folder) setSite(self.folder1_1) events = [] ztapi.subscribe([IIntIdRemovedEvent], None, events.append) # This should unregister the object in all utilities, not just the # nearest one. removeIntIdSubscriber(folder, ObjectRemovedEvent(parent_folder)) self.assertRaises(KeyError, self.utility.getObject, id) self.assertRaises(KeyError, self.utility1.getObject, id1) self.assertEquals(len(events), 1) self.assertEquals(events[0].object, folder) self.assertEquals(events[0].original_event.object, parent_folder)
def migrateToFive15(self): all_utilities = self.context.utilities.objectItems() self.unmakeSite() self.context.manage_delObjects(['utilities']) components_view = queryMultiAdapter((self.context, self.request), Interface, 'components.html') components_view.makeSite() setSite(self.context) site_manager = getSiteManager() for id, utility in all_utilities: info = id.split('-') if len(info) == 1: name = '' else: name = info[1] interface_name = info[0] for iface in providedBy(utility): if iface.getName() == interface_name: site_manager.registerUtility(utility, iface, name=name) return "Migration done!"
def readme_setup(tc): # XXX duplicates simple_setup? tc._refreshSkinData() tc.request = tc.app.REQUEST tc.response = tc.request.RESPONSE tc.homepage = getattr(tc.portal, 'site-home') tc.projects = tc.portal.projects setSite(tc.portal)
def purge(event): """Asynchronously send PURGE requests """ request = event.request context = event.object annotations = IAnnotations(request, None) if annotations is None: return paths = annotations.get(KEY, None) if paths is None or not paths: return setSite(getattr(IComponentLookup(context, None), '__parent__')) if not isCachePurgingEnabled(context): return purger = queryUtility(IPurger, context=context) if purger is None: return settings = getUtility(ICachePurgingConfiglet, context=context) for path in paths: for url in getURLsToPurge(path, settings.cachingProxies): purger.purgeAsync(url) setSite(None)
def setNodeText(self, jid, node, text): transaction.begin() app = Zope2.app() try: try: portal = app.unrestrictedTraverse(self.portal_id, None) if portal is None: raise DSCException( 'Portal with id %s not found' % self.portal_id) setSite(portal) acl_users = getToolByName(portal, 'acl_users') user_id = JID(jid).user user = acl_users.getUserById(user_id) if user is None: raise DSCException( 'Invalid user %s' % user_id) newSecurityManager(None, user) ct = getToolByName(portal, 'portal_catalog') uid, html_id = node.split('#') item = ct.unrestrictedSearchResults(UID=uid) if not item: raise DSCException( 'Content with UID %s not found' % uid) item = ICollaborativelyEditable(item[0].getObject()) item.setNodeTextFromHtmlID(html_id, text) transaction.commit() except: transaction.abort() raise finally: noSecurityManager() setSite(None) app._p_jar.close() return text
def setUp(self): super(TestForwardingTransitionController, self).setUp() # we need to have a site root for making the get_client_id cachecky # work. root = self.create_dummy(getSiteManager=getSiteManager, id='root') alsoProvides(root, IPloneSiteRoot) setSite(root)
def test_getSiteManager(self): self.assertEqual(getSiteManager(None), getGlobalSiteManager()) self.assertEqual(getSiteManager(self.root), getGlobalSiteManager()) self.assertEqual(getSiteManager(self.f1), self.sm1) self.assertEqual(getSiteManager(self.f2), self.sm2) setSite(self.f2) self.assertEqual(getSiteManager(None), self.sm2)
def test_dancefloor_collectors(self): # we're on the dancefloor hooks.setSite(self.dancefloor) name = get_name_for_site(self.dancefloor) util = component.getUtility(ILocalNewsletterLookup, name=name) collectors = sorted([c.id for c in util.local_collectors()]) self.assertEqual(collectors, sorted(self.subfloor.collectors.keys()))
def test_subfloor_channels(self): # we're on the subfloor hooks.setSite(self.subfloor) name = get_name_for_site(self.subfloor) util = component.getUtility(ILocalNewsletterLookup, name=name) channels = sorted([c.name for c in util.local_channels()]) self.assertEqual(channels, sorted(self.subfloor.channels.keys()))
def setUp(test): functional.FunctionalTestSetup().setUp() newInteraction() def fake_utcnow(self): return datetime.datetime(2015, 7, 30, 8, 0, 0) curse(datetime.datetime, 'utcnow', classmethod(fake_utcnow)) root = functional.getRootFolder() setSite(root) sm = root.getSiteManager() # IIntIds root['intids'] = IntIds() sm.registerUtility(root['intids'], IIntIds) root['intids'].register(root) # catalog root['catalog'] = Catalog() sm.registerUtility(root['catalog'], ICatalog) # PluggableAuthentication pau = PluggableAuthentication(u'') event.notify(ObjectCreatedEvent(pau)) sm[u'auth'] = pau sm.registerUtility(pau, IAuthentication) # Credentials Plugin defaultCreds.install() defaultCreds.activate() # people people = PersonalSpaceManager(title=u'People') event.notify(ObjectCreatedEvent(people)) root['people'] = people sm.registerUtility(root['people'], IPersonalSpaceManager) user = sm.getUtility(IAuthentication).getPrincipal('zope.mgr') people.assignPersonalSpace(user) user = sm.getUtility(IAuthentication).getPrincipal('zope.user') people.assignPersonalSpace(user) # default content content = Content(u'Content1', u'Some Content1') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content1'] = content content = Content(u'Content2', u'Some Content2') event.notify(ObjectCreatedEvent(content)) IOwnership(content).ownerId = 'zope.user' root['content2'] = content endInteraction()
def setUpDataManager(test): tearDownPlaces(test) test.globs = {'root': placefulSetUp(True)} # placeful setup root = test.globs['root'] setUpZCML(test) hooks.setSite(root) testing.generateCategorizableItemDescriptions(root) from zope.security.management import newInteraction interaction = newInteraction()
def enableLocalSiteHook(obj): warnings.warn("The enableLocalSiteHook is deprecated and will be removed " "in Zope 2.12. \nSee Five/doc/localsite.txt .", DeprecationWarning, 2) enableSite(obj) components = FiveSiteManager(obj) obj.setSiteManager(components) setSite(obj) setHooks()
def setUp(self): super(TestImageLaTeXGenerator, self).setUp() self.image = self.create_dummy( get_size=lambda: 11, data='hello world') self.context = self.create_dummy( UID=lambda: 'XUID') setSite(self._create_site_with_request())
def main(): global app attr_storage = AttributeStorage() fss_storage = FileSystemStorage() app = makerequest(app) _policy = PermissiveSecurityPolicy() _oldpolicy = setSecurityPolicy(_policy) newSecurityManager(None, OmnipotentUser().__of__(app.acl_users)) global portal, ct portal = app[ploneid] setSite(portal) # Initialization log('Initialized at', datetime.now().isoformat()) ct = getToolByName(portal, 'portal_catalog') fssfiles = ct.searchResults({'portal_type': pt}) for fssfile in fssfiles: log('Migrating: [%s] %s in %s ... ' % (fssfile.portal_type, fssfile.id, fssfile.getPath())) obj = portal.restrictedTraverse(fssfile.getPath()) try: f_tp = 'image' field = obj.Schema()[f_tp] except KeyError, e: f_tp = 'file' field = obj.Schema()[f_tp] fieldstorage = field.storage try: mimetype = field.getContentType(obj) except: mimetype = obj.getContentType() content = StringIO(str(fss_storage.get(f_tp, obj))) # Cleaning the storage fss_storage.unset(f_tp, obj) field.set(obj, content) field.setContentType(obj, mimetype) field.setFilename(obj, obj.id) log('Transaction commit and Data.fs synchronism.') transaction.commit() app._p_jar.sync()
def unregisterUtilities(context): portal = context.getSite() setSite(portal) sm = getSiteManager(portal) queue_name = 'collective.pdfpeek.conversion_' + portal.id queue = queryUtility(IQueue, queue_name) if queue is not None: queue_utility = getUtility(IQueue, queue_name) sm.unregisterUtility(queue_utility, IQueue) del queue_utility logger.info("Removed PDFpeek Queue")
def setUp(self): BaseRegistryTests.setUp(self) setHooks() self.root.site = Folder(id='site') self.site = self.root.site gen = PloneGenerator() gen.enableSite(self.site) setSite(self.site) sm = getSiteManager(self.site) sm.registerUtility(MarscatsSettingsStorage(), IMarscatsSettingsStorage) self.storage = getUtility(IMarscatsSettingsStorage)
def setupUtilities(site): """ Register a local utility """ if not ISite.providedBy(site): enableLocalSiteHook(site) setSite(site) sm = getSiteManager() if not sm.queryUtility(IZipFileTransportUtility): sm.registerUtility(ZipFileTransportUtility('zipfiletransport'), IZipFileTransportUtility)