def testSetUp(cls): import Products zcml.load_config('meta.zcml', Products.Five) zcml.load_config('event.zcml', Products.Five) zcml.load_config('event.zcml', Products.CMFUid) setHooks()
def __call__(self, config_file, run_as, server_url=None, context_path=None, portal_id=None, **environ): Zope2.Startup.run.configure(config_file) environ['SERVER_URL'] = server_url self.app = makerequest(Zope2.app(), environ=environ) setHooks() if portal_id is not None: self.portal = self.app[portal_id] else: portals = self.app.objectValues('Plone Site') if len(portals) > 1: log.warn('More than one portal - using first one') self.portal = portals[0] setSite(self.portal) self.app.REQUEST.other['PARENTS'] = [self.portal, self.app] self.app.REQUEST.other['VirtualRootPhysicalPath'] = ( '', self.portal.id) log.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) log.addHandler(handler) with api.env.adopt_user(username=run_as): if context_path is not None: self.context = self.portal.restrictedTraverse(context_path) else: self.context = self.portal self.run() transaction.commit()
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal)
def setUp(self): """Test setUp based on z3c.form.testing.setUp minus their globals. """ from zope.component.testing import setUp setUp() from zope.container.testing import setUp setUp() from zope.component import hooks hooks.setHooks() from zope.traversing.testing import setUp setUp() from zope.publisher.browser import BrowserLanguages from zope.publisher.interfaces.http import IHTTPRequest from zope.i18n.interfaces import IUserPreferredLanguages import zope.component zope.component.provideAdapter( BrowserLanguages, [IHTTPRequest], IUserPreferredLanguages) from zope.site.folder import rootFolder site = rootFolder() from zope.site.site import LocalSiteManager from zope.component.interfaces import ISite if not ISite.providedBy(site): site.setSiteManager(LocalSiteManager(site)) hooks.setSite(site)
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 = Mock( wraps=PersistentComponents(bases=(getGlobalSiteManager(),))) from zope.component.hooks import getSiteManager self.patch_global(getSiteManager, return_value=site_manager_mock) # 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.assertEqual(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertEqual(None, queryUtility(IFactory, name=portal_type))
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.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 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.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 testSetUp(cls): import Products.Five import zope.traversing zcml.load_config('meta.zcml', Products.Five) zcml.load_config('configure.zcml', zope.traversing) setHooks()
def setUp(cls): app = ztc.app() portal = app.plone # change the active local site manager setHooks() setSite(portal) # elevate permissions user = portal.getWrappedOwner() newSecurityManager(None, user) tool = getToolByName(portal, 'portal_quickinstaller') product_name = 'quintagroup.plonetabs' if tool.isProductInstalled(product_name): tool.uninstallProducts([ product_name, ]) # drop elevated perms noSecurityManager() transaction.commit() ztc.close(app)
def ploneSite(db=None, connection=None, environ=None): """Context manager for working with the Plone portal during layer setup:: with ploneSite() as portal: ... This is based on the ``z2.zopeApp()`` context manager. See the module ``plone.testing.z2`` for details. Do not use this in a test. Use the 'portal' resource from the PloneFixture layer instead! Pass a ZODB handle as ``db`` to use a specificdatabase. Alternatively, pass an open connection as ``connection`` (the connection will not be closed). """ setHooks() site = getSite() with z2.zopeApp(db, connection, environ) as app: portal = app[PLONE_SITE_ID] setSite(portal) login(portal, TEST_USER_NAME) try: yield portal finally: logout() if site is not portal: setSite(site)
def pushGlobalRegistry(portal, new=None, name=None): """Set a new global component registry that uses the current registry as a base. If you use this, you *must* call ``popGlobalRegistry()`` to restore the original state. If ``new`` is not given, a new registry is created. If given, you must provide a ``zope.component.globalregistry.BaseGlobalComponents`` object. Returns the new registry. Also ensure that the persistent component registry at ``portal`` has the new global registry as its base. """ site = getSite() localSiteManager = portal.getSiteManager() current = zca.pushGlobalRegistry(new=new) if current not in localSiteManager.__bases__: localSiteManager.__bases__ = (current, ) if site is not None: setHooks() setSite(site) return current
def tearDown(self): with z2.zopeApp() as app: portal = app[PLONE_SITE_ID] setHooks() setSite(portal) # Allow subclass to tear down persistent fixture self.tearDownPloneSite(portal) setSite(None) # Make sure zope.security checkers can be set up and torn down # reliably security.popCheckers() # Pop the component registry, thus removing component # architecture registrations popGlobalRegistry(portal) # Remove PAS plugins self.tearDownMultiPlugins() # Allow subclass to tear down products self.tearDownZope(app) # Zap the configuration context del self['configurationContext'] # Pop the demo storage, thus restoring the database to the # previous state self['zodbDB'].close() del self['zodbDB']
def setUp(test): from zope.component.testing import setUp setUp() from zope.container.testing import setUp setUp() from zope.component import hooks hooks.setHooks() from zope.traversing.testing import setUp setUp() from zope.publisher.browser import BrowserLanguages from zope.publisher.interfaces.http import IHTTPRequest from zope.i18n.interfaces import IUserPreferredLanguages zope.component.provideAdapter(BrowserLanguages, [IHTTPRequest], IUserPreferredLanguages) from zope.site.folder import rootFolder site = rootFolder() from zope.site.site import LocalSiteManager from zope.component.interfaces import ISite if not ISite.providedBy(site): site.setSiteManager(LocalSiteManager(site)) hooks.setSite(site) test.globs = { 'print_function': print_function, 'root': site, 'pprint': pprint.pprint}
def setUp(self): """Test setUp based on z3c.form.testing.setUp minus their globals. """ from zope.component.testing import setUp setUp() from zope.container.testing import setUp setUp() from zope.component import hooks hooks.setHooks() from zope.traversing.testing import setUp setUp() from zope.publisher.browser import BrowserLanguages from zope.publisher.interfaces.http import IHTTPRequest from zope.i18n.interfaces import IUserPreferredLanguages import zope.component zope.component.provideAdapter(BrowserLanguages, [IHTTPRequest], IUserPreferredLanguages) from zope.site.folder import rootFolder site = rootFolder() from zope.site.site import LocalSiteManager from zope.component.interfaces import ISite if not ISite.providedBy(site): site.setSiteManager(LocalSiteManager(site)) hooks.setSite(site)
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.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 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 = Mock(wraps=PersistentComponents( bases=(getGlobalSiteManager(), ))) from zope.component.hooks import getSiteManager self.patch_global(getSiteManager, return_value=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'. 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_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 = Mock(wraps=PersistentComponents( bases=(getGlobalSiteManager(), ))) from zope.component.hooks import getSiteManager self.patch_global(getSiteManager, return_value=site_manager_mock) # 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.assertEqual(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertEqual(None, queryUtility(IFactory, name=portal_type))
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 = Mock(wraps=PersistentComponents( bases=(getGlobalSiteManager(), ))) from zope.component.hooks import getSiteManager self.patch_global(getSiteManager, return_value=site_manager_mock) ftiAdded(fti, ObjectAddedEvent(fti, container_dummy, fti.getId())) args1, kwargs1 = site_manager_mock.registerUtility.call_args_list[0] self.assertEqual(args1, (fti, IDexterityFTI, portal_type)) self.assertEqual(kwargs1, {'info': 'plone.dexterity.dynamic'}) args2, kwargs2 = site_manager_mock.registerUtility.call_args_list[1] self.assertIsInstance(args2[0], DexterityFactory) self.assertEqual(args2[0].portal_type, portal_type) self.assertEqual(args2[1:], (IFactory, portal_type)) self.assertEqual(kwargs2, {'info': 'plone.dexterity.dynamic'}) 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_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.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 setUp(self): portal = self.layer["portal"] self.portal = portal self.request = self.layer["request"] setRoles(portal, TEST_USER_ID, ["Manager"]) setHooks() setSite(portal)
def pushGlobalRegistry(new=None): """Set a new global component registry that uses the current registry as a a base. If you use this, you *must* call ``popGlobalRegistry()`` to restore the original state. If ``new`` is not given, a new registry is created. If given, you must provide a ``zope.component.globalregistry.BaseGlobalComponents`` object. Returns the new registry. """ from zope.component import globalregistry # Save the current top of the stack in a registry current = globalregistry.base # The first time we're called, we need to put the default global # registry at the bottom of the stack, and then patch the class to use # the stack for loading pickles. Otherwise, we end up with POSKey and # pickling errors when dealing with persistent registries that have the # global registry (globalregistry.base) as a base if len(_REGISTRIES) == 0: _REGISTRIES.append(current) globalregistry.BaseGlobalComponents._old__reduce__ = ( globalregistry.BaseGlobalComponents.__reduce__) globalregistry.BaseGlobalComponents.__reduce__ = ( lambda self: (loadRegistry, (self.__name__,))) if new is None: name = 'test-stack-{0}'.format(len(_REGISTRIES)) new = globalregistry.BaseGlobalComponents(name=name, bases=(current,)) logger.debug( 'New component registry: %s based on %s', name, current.__name__) else: logger.debug('Push component registry: %s', new.__name__) _REGISTRIES.append(new) # Monkey patch this into the three (!) places where zope.component # references it as a module global variable _hookRegistry(new) # Reset the site manager hook so that getSiteManager() returns the base # again from zope.component import getSiteManager getSiteManager.reset() try: from zope.component.hooks import setSite, setHooks except ImportError: pass else: setSite() setHooks() return new
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] alsoProvides(self.request, IPloneFormLayer) setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal)
def testSetUp(cls): import Products import OFS zcml.load_config('meta.zcml', Products.Five) zcml.load_config('event.zcml', OFS) zcml.load_config('event.zcml', Products.CMFUid) setHooks()
def _placefulSetUp(portal): '''Sets the local site/manager.''' try: from zope.component.hooks import setHooks, setSite except ImportError: from zope.app.component.hooks import setHooks, setSite setHooks() setSite(portal)
def setUp(self): setHooks() context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in self.features: context.provideFeature(feature) self.context = self._load_zcml(context) provideHandler(events.append, (None, ))
def setUp(self): setHooks() context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in self.features: context.provideFeature(feature) self.context = self._load_zcml(context) provideHandler(events.append, (None,))
def __init__(self, paster_variables): setHooks() self.paster = toargs(self, IPasterVariables, paster_variables) getGlobalSiteManager().registerUtility(provided=IConfiguration, component=self) load_configuration(self.paster['configure_zcml'])
def _placefulSetUp(portal): '''Sets the local site/manager.''' from zope.component.hooks import setHooks, setSite from zope.component.interfaces import ComponentLookupError setHooks() try: setSite(portal) except ComponentLookupError: pass
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] wftool = getToolByName(self.portal, "portal_workflow") wftool.setDefaultChain("simple_publication_workflow") setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal)
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.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.assertEqual('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 setUpAjaxView(test=None): setHooks() zope.component.provideAdapter(CommandInspectorView, adapts=(IKSSCommands, IBrowserRequest)) registerPlugin(Action, IAction, 'replaceInnerHTML', None, 'selector', 'html', [], None) zope.component.provideAdapter(KSSCoreCommands, adapts=(IKSSView,), provides=IKSSCoreCommands) registerPlugin(CommandSet, ICommandSet, 'core', IKSSCoreCommands)
def setup_config(package, zcml_file): zcml_file = os.path.join(os.path.dirname(package.__file__), zcml_file) setHooks() context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) return xmlconfig.file(zcml_file, package=package, context=context, execute=True)
def setUp(app): # enable zcml and site hooks placeless.setUp() import Products.Five from five import intid zcml.load_config('meta.zcml', Products.Five) zcml.load_config('configure.zcml', Products.Five) zcml.load_config('configure.zcml', intid) zcml.load_config('test.zcml', intid) setHooks()
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] self.wft = getToolByName(self.portal, 'portal_workflow') setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal) set_env_timezone(TZNAME) set_timezone(TZNAME)
def setUp(cls): import Products zcml.load_site(force=True) setHooks() # Register Model Catalog related stuff init_model_catalog_for_tests() component.provideHandler(eventlog.trace, (ITestItem, IObjectEvent)) component.provideHandler(eventlog.trace, (IRelationship, IObjectEvent))
def testSetUp(cls): import OFS import Products.Five import zope.traversing zcml.load_config('meta.zcml', Products.Five) zcml.load_config('configure.zcml', zope.traversing) zcml.load_config('event.zcml', OFS) zcml.load_config('event.zcml', Products.CMFCore) zcml.load_config('tool.zcml', Products.CMFCore) setHooks()
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] self.wft = getToolByName(self.portal, 'portal_workflow') setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal) # Make sure Events use simple_publication_workflow self.portal.portal_workflow.setChainForPortalTypes(['Event'], ['simple_publication_workflow'])
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] self.wft = getToolByName(self.portal, 'portal_workflow') setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal) # Make sure Events use simple_publication_workflow self.portal.portal_workflow.setChainForPortalTypes( ['Event'], ['simple_publication_workflow'])
def setUp(self): try: # Push a new database storage so that database changes # commited during layer setup can be easily torn down self['zodbDB'] = zodb.stackDemoStorage(self.get('zodbDB'), name=self.__name__) # Push a new configuration context so that it's possible to # re-import ZCML files after tear-down name = self.__name__ if self.__name__ is not None else 'not-named' contextName = 'PloneSandboxLayer-{0}'.format(name) self['configurationContext'] = configurationContext = ( zca.stackConfigurationContext(self.get('configurationContext'), name=contextName)) with ploneSite() as portal: setHooks() # Make sure there's no local site manager while we load ZCML setSite(None) # Push a new component registry so that ZCML registations # and other global component registry changes are sandboxed pushGlobalRegistry(portal) # Persist GenericSetup profile upgrade versions for easy # rollback. persist_profile_upgrade_versions(portal) # Make sure zope.security checkers can be set up and torn down # reliably security.pushCheckers() from Products.PluggableAuthService.PluggableAuthService import MultiPlugins # noqa preSetupMultiPlugins = MultiPlugins[:] # Allow subclass to load ZCML and products self.setUpZope(portal.getPhysicalRoot(), configurationContext) # Allow subclass to configure a persistent fixture setSite(portal) self.setUpPloneSite(portal) setSite(None) # Keep track of PAS plugins that were added during setup self.snapshotMultiPlugins(preSetupMultiPlugins) except Exception: del self['configurationContext'] self['zodbDB'].close() del self['zodbDB'] raise
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 = Mock( wraps=PersistentComponents(bases=(getGlobalSiteManager(),))) from zope.component.hooks import getSiteManager self.patch_global(getSiteManager, return_value=site_manager_mock) self.assertEqual( 'string:${folder_url}/++add++testtype', fti.add_view_expr ) ftiRenamed( fti, ObjectMovedEvent( fti, container_dummy, fti.getId(), container_dummy, u"newtype" ) ) # First look for unregistration of all local components site_manager_mock.unregisterUtility.assert_called_once_with( provided=IDexterityFTI, name=portal_type ) # Then look for re-registration of global components self.assertEquals(site_manager_mock.registerUtility.call_count, 2) 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_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 = Mock( wraps=PersistentComponents(bases=(getGlobalSiteManager(),))) from zope.component.hooks import getSiteManager self.patch_global(getSiteManager, return_value=site_manager_mock) self.assertEqual( 'string:${folder_url}/++add++testtype', fti.add_view_expr ) ftiRenamed( fti, ObjectMovedEvent( fti, container_dummy, fti.getId(), container_dummy, u"newtype" ) ) # First look for unregistration of all local components site_manager_mock.unregisterUtility.assert_called_once_with( provided=IDexterityFTI, name=portal_type ) # Then look for re-registration of global components self.assertEqual(site_manager_mock.registerUtility.call_count, 2) site_dummy = self.create_dummy( getSiteManager=lambda: site_manager_mock ) setSite(site_dummy) setHooks() self.assertNotEqual( None, queryUtility(IDexterityFTI, name=portal_type) ) self.assertNotEqual(None, queryUtility(IFactory, name=portal_type))
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] self.wft = getToolByName(self.portal, 'portal_workflow') setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal) self.maxclient, settings = getUtility(IMAXClient)() self.username = settings.max_restricted_username self.token = settings.max_restricted_token self.maxclient.setActor(settings.max_restricted_username) self.maxclient.setToken(settings.max_restricted_token)
def setUp(self): # Create and enable a local component registry site = Folder() createComponentRegistry(site) setHooks() setSite(site) sm = getSiteManager() tool = DummyTool() site._setObject(tool.id, tool) tool2 = DummyTool2() site._setObject(tool2.id, tool2) self._obj = sm self._BODY = _COMPONENTS_BODY
def setUp(self): portal = self.layer['portal'] self.portal = portal self.request = self.layer['request'] setRoles(portal, TEST_USER_ID, ['Manager']) setHooks() setSite(portal) set_timezone("Australia/Brisbane") # TODO: don't use admin privileges for test methods except # test_prev_events_link and test_prev_events_link_and_navigation_root # Make sure Events use simple_publication_workflow self.portal.portal_workflow.setChainForPortalTypes( ['Event'], ['simple_publication_workflow'])
def test_components_registered_on_add(self): portal_type = '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, Interface) site_manager_mock = self.mocker.proxy( PersistentComponents(bases=(getGlobalSiteManager(), ))) getSiteManager_mock = self.mocker.replace( 'zope.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 testSetUp(cls): import Zope2.App import AccessControl import Products.Five import Products.GenericSetup import Products.CMFCore import Products.CMFCore.exportimport zcml.load_config('meta.zcml', Zope2.App) zcml.load_config('meta.zcml', Products.Five) zcml.load_config('permissions.zcml', AccessControl) zcml.load_config('permissions.zcml', Products.Five) zcml.load_config('meta.zcml', Products.GenericSetup) zcml.load_config('configure.zcml', Products.GenericSetup) zcml.load_config('permissions.zcml', Products.CMFCore) zcml.load_config('tool.zcml', Products.CMFCore) zcml.load_config('configure.zcml', Products.CMFCore.exportimport) zcml.load_string(_DUMMY_ZCML) setHooks()
def setUp(cls): metaconfigure.debug_mode = True import plone.app.dexterity zcml.load_config('meta.zcml', plone.app.dexterity) zcml.load_config('configure.zcml', plone.app.dexterity) metaconfigure.debug_mode = False # import the default profile root = app() portal = root.plone setHooks() setSite(portal) tool = getToolByName(portal, 'portal_setup') profile = 'profile-plone.app.dexterity:default' tool.runAllImportStepsFromProfile(profile, purge_old=False) setSite(None) # and commit the changes commit() close(root)
def test_global_components_not_unregistered_on_delete(self): portal_type = '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, Interface) site_manager_mock = self.mocker.proxy( PersistentComponents(bases=(getGlobalSiteManager(), ))) getSiteManager_mock = self.mocker.replace( 'zope.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_components_unregistered_on_delete(self): portal_type = '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, Interface) site_manager_mock = self.mocker.proxy( PersistentComponents(bases=(getGlobalSiteManager(), ))) getSiteManager_mock = self.mocker.replace( 'zope.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.assertEqual(None, queryUtility(IDexterityFTI, name=portal_type)) self.assertEqual(None, queryUtility(IFactory, name=portal_type))
def popGlobalRegistry(): """Restore the global component registry form the top of the stack, as set with ``pushGlobalRegistry()``. """ from zope.component import globalregistry if not _REGISTRIES or not _REGISTRIES[-1] is globalregistry.base: msg = ("popGlobalRegistry() called out of sync with " "pushGlobalRegistry()") raise ValueError(msg) current = _REGISTRIES.pop() previous = current.__bases__[0] # If we only have the default registry on the stack, return it to its # original state and empty the stack if len(_REGISTRIES) == 1: assert _REGISTRIES[0] is previous _REGISTRIES.pop() globalregistry.BaseGlobalComponents.__reduce__ = ( globalregistry.BaseGlobalComponents._old__reduce__) _hookRegistry(previous) # Reset the site manager hook so that getSiteManager() returns the base # again from zope.component import getSiteManager getSiteManager.reset() try: from zope.component.hooks import setSite, setHooks except ImportError: pass else: setSite() setHooks() return previous
def configureComponents(self, options, site_zcml=None): """Configure Zope 3 components.""" # Hook up custom component architecture calls setHooks() context = zope.configuration.config.ConfigurationMachine() for config, handler in plugin_configurations: if handler is not None: handler(options, context) if options.config.devmode: context.provideFeature('devmode') zope.configuration.xmlconfig.registerCommonDirectives(context) if site_zcml is None: site_zcml = options.config.site_definition context = zope.configuration.xmlconfig.file(site_zcml, context=context) # Store the configuration context from zope.app.appsetup import appsetup appsetup.__dict__['__config_context'] = context
def __call__(self, config_file, run_as, server_url=None, context_path=None, portal_id=None, **environ): Zope2.Startup.run.configure(config_file) environ['SERVER_URL'] = server_url self.app = makerequest(Zope2.app(), environ=environ) setHooks() if portal_id is not None: self.portal = self.app[portal_id] else: portals = self.app.objectValues('Plone Site') if len(portals) > 1: log.warn('More than one portal - using first one') self.portal = portals[0] setSite(self.portal) self.app.REQUEST.other['PARENTS'] = [self.portal, self.app] self.app.REQUEST.other['VirtualRootPhysicalPath'] = ('', self.portal.id) log.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) log.addHandler(handler) with api.env.adopt_user(username=run_as): if context_path is not None: self.context = self.portal.restrictedTraverse(context_path) else: self.context = self.portal self.run() transaction.commit()