def test_w_file_passed(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration import tests from zope.configuration.tests import simple context = ConfigurationMachine() registerCommonDirectives(context) before_stack = context.stack[:] context.package = tests fqn = _packageFile(tests, 'simple.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context, 'simple.zcml') self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s', (fqn,), {})) self.assertEqual(len(context.actions), 3) action = context.actions[0] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqn,)) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.py')) action = context.actions[1] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqn,)) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.zcml')) action = context.actions[2] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqn,)) self.assertEqual(action['args'][0].path, _packageFile(tests, '__init__.py')) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 1) self.assertIn(fqn, context._seen_files)
def load_zcml(self, zcml_asset_specification): def _get_site_manager(context=None): return self if ':' not in zcml_asset_specification: import alpaca config_package = alpaca config_file = zcml_asset_specification else: package_name, config_file = zcml_asset_specification.split(':') __import__(package_name) config_package = sys.modules[package_name] context = ConfigurationMachine() context.package = config_package xmlconfig.registerCommonDirectives(context) xmlconfig.file( config_file, package=config_package, context=context, execute=False ) getSiteManager.sethook(_get_site_manager) try: context.execute_actions() finally: getSiteManager.reset()
def __new__(self, features=None): context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in (features or []): context.provideFeature(feature) interface.alsoProvides(context, ISparcPreparedConfigurationContext) return context
def configure(arguments): # Enable venuasianconfiguration if HAS_VENUSIANCONFIGURATION: import venusianconfiguration venusianconfiguration.enable() # BBB: Support Zope's global configuration context if HAS_ZOPE: try: import Zope2.App.zcml config = Zope2.App.zcml._context or ConfigurationMachine() except (ImportError, AttributeError): config = ConfigurationMachine() else: config = ConfigurationMachine() # Parse and evaluate configuration and plugins registerCommonDirectives(config) import transmogrifier xmlconfig.include(config, package=transmogrifier, file='meta.zcml') xmlconfig.include(config, package=transmogrifier, file='configure.zcml') # Resolve includes for include in set(arguments.get('--include')): package, filename = parse_include(include) if package and filename: package = importlib.import_module(package) xmlconfig.include(config, package=package, file=filename) elif package and HAS_VENUSIANCONFIGURATION: # Support including single module in the current working directory import venusianconfiguration venusianconfiguration.venusianscan(package, config) config.execute_actions()
def test_w_file_passed(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration import tests from zope.configuration.tests import simple context = ConfigurationMachine() registerCommonDirectives(context) before_stack = context.stack[:] context.package = tests fqn = _packageFile(tests, 'simple.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context, 'simple.zcml') self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s' % fqn, (), {})) self.assertEqual(len(context.actions), 3) action = context.actions[0] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqn, )) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.py')) action = context.actions[1] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqn, )) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.zcml')) action = context.actions[2] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqn, )) self.assertEqual(action['args'][0].path, _packageFile(tests, '__init__.py')) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 1) self.assertIn(fqn, context._seen_files)
def configure(arguments): # Enable venuasianconfiguration if HAS_VENUSIANCONFIGURATION: import venusianconfiguration venusianconfiguration.enable() # BBB: Support Zope's global configuration context if HAS_ZOPE: try: import Zope2.App.zcml config = Zope2.App.zcml._context or ConfigurationMachine() except (ImportError, AttributeError): config = ConfigurationMachine() else: config = ConfigurationMachine() # Parse and evaluate configuration and plugins registerCommonDirectives(config) import transmogrifier xmlconfig.include(config, package=transmogrifier, file='meta.zcml') xmlconfig.include(config, package=transmogrifier, file='configure.zcml') # Resolve includes for include in set(arguments.get('--include')): package, filename = parse_include(include) if package and filename: package = importlib.import_module(package) xmlconfig.include(config, package=package, file=filename) elif package and HAS_VENUSIANCONFIGURATION: # Support including single module in the current working directory import venusianconfiguration venusianconfiguration.venusianscan(package, config) config.execute_actions()
def test_w_files_passed_and_package(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() registerCommonDirectives(context) before_stack = context.stack[:] fqn1 = _packageFile(samplepackage, 'baz1.zcml') fqn2 = _packageFile(samplepackage, 'baz2.zcml') fqn3 = _packageFile(samplepackage, 'baz3.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context, package=samplepackage, files='baz*.zcml') self.assertEqual(len(logger.debugs), 3) self.assertEqual(logger.debugs[0], ('include %s', (fqn1, ), {})) self.assertEqual(logger.debugs[1], ('include %s', (fqn2, ), {})) self.assertEqual(logger.debugs[2], ('include %s', (fqn3, ), {})) self.assertEqual(len(context.actions), 2) action = context.actions[0] self.assertEqual(action['callable'], foo.data.append) self.assertEqual(action['includepath'], (fqn2, )) self.assertIsInstance(action['args'][0], foo.stuff) self.assertEqual(action['args'][0].args, (('x', (b'foo')), ('y', 2))) action = context.actions[1] self.assertEqual(action['callable'], foo.data.append) self.assertEqual(action['includepath'], (fqn3, )) self.assertIsInstance(action['args'][0], foo.stuff) self.assertEqual(action['args'][0].args, (('x', (b'foo')), ('y', 3))) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 3) self.assertIn(fqn1, context._seen_files) self.assertIn(fqn2, context._seen_files) self.assertIn(fqn3, context._seen_files)
def _make_context(self, autocommit=False): context = PyramidConfigurationMachine() registerCommonDirectives(context) context.registry = self.registry context.autocommit = autocommit context.route_prefix = self.route_prefix return context
def test_w_files_passed_and_package(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() registerCommonDirectives(context) before_stack = context.stack[:] fqn1 = _packageFile(samplepackage, 'baz1.zcml') fqn2 = _packageFile(samplepackage, 'baz2.zcml') fqn3 = _packageFile(samplepackage, 'baz3.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context, package=samplepackage, files='baz*.zcml') self.assertEqual(len(logger.debugs), 3) self.assertEqual(logger.debugs[0], ('include %s', (fqn1,), {})) self.assertEqual(logger.debugs[1], ('include %s', (fqn2,), {})) self.assertEqual(logger.debugs[2], ('include %s', (fqn3,), {})) self.assertEqual(len(context.actions), 2) action = context.actions[0] self.assertEqual(action['callable'], foo.data.append) self.assertEqual(action['includepath'], (fqn2,)) self.assertIsInstance(action['args'][0], foo.stuff) self.assertEqual(action['args'][0].args, (('x', (b'foo')), ('y', 2))) action = context.actions[1] self.assertEqual(action['callable'], foo.data.append) self.assertEqual(action['includepath'], (fqn3,)) self.assertIsInstance(action['args'][0], foo.stuff) self.assertEqual(action['args'][0].args, (('x', (b'foo')), ('y', 3))) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 3) self.assertIn(fqn1, context._seen_files) self.assertIn(fqn2, context._seen_files) self.assertIn(fqn3, context._seen_files)
def _configure(self=None, set_up_packages=(), features=(), context=None, execute=True): if set_up_packages: if context is None: context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in features: context.provideFeature(feature) for i in set_up_packages: __traceback_info__ = (i, self, set_up_packages) if isinstance(i, tuple): filename = i[0] package = i[1] else: filename = 'configure.zcml' package = i if isinstance(package, six.string_types): package = dottedname.resolve(package) context = xmlconfig.file(filename, package=package, context=context, execute=execute) return context
def __main__(): # Enable logging logging.basicConfig(level=logging.INFO) # Parse cli arguments arguments = docopt(__doc__) # Parse and evaluate configuration and plugins config = ConfigurationMachine() registerCommonDirectives(config) xmlconfig.include(config, package=collective.transmogrifier, file='meta.zcml') xmlconfig.include(config, package=collective.transmogrifier, file='configure.zcml') config.execute_actions() if arguments.get('--list'): blueprints = dict(getUtilitiesFor(ISectionBlueprint)) pipelines = map(configuration_registry.getConfiguration, configuration_registry.listConfigurationIds()) print """ Available blueprints -------------------- {0:s} Available pipelines ------------------- {1:s} """.format('\n'.join(sorted(blueprints.keys())), '\n'.join(['{0:s}\n {1:s}: {2:s}'.format( p['id'], p['title'], p['description']) for p in pipelines])) return # Load optional overrides overrides = {} overrides_path = arguments.get('--overrides') if overrides_path and not os.path.isabs(overrides_path): overrides_path = os.path.join(os.getcwd(), overrides_path) if overrides_path: parser = ConfigParser.RawConfigParser() parser.optionxform = str # case sensitive with open(overrides_path) as fp: parser.readfp(fp) overrides.update(dict(((section, dict(parser.items(section))) for section in parser.sections()))) # Initialize optional context context_path = arguments.get('--context') if context_path is None: context = dict() else: context_module_path, context_class_name = context_path.rsplit('.', 1) context_module = importlib.import_module(context_module_path) context = getattr(context_module, context_class_name)() # Transmogrify for pipeline in arguments.get('<pipeline>'): ITransmogrifier(context)(pipeline, **overrides)
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 load_configuration(zcml, features=()): logging.info('Loading configuration from %s' % zcml) context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in features: context.provideFeature(feature) context = xmlconfig.file(zcml, context=context, execute=True) return context
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 stackConfigurationContext(context=None, name='not named'): """Return a new ``ConfigurationMachine`` configuration context that is a clone of the passed-in context. If no context is passed in, a fresh configuration context is returned. """ from copy import deepcopy from zope.interface import Interface from zope.interface.adapter import AdapterRegistry from zope.configuration.xmlconfig import registerCommonDirectives clone = NamedConfigurationMachine(name) # Prime this so that the <meta:redefinePermission /> directive won't lose # track of it across our stacked configuration machines clone.permission_mapping = {} if context is None: registerCommonDirectives(clone) logger.debug('New configuration context %s', clone) return clone # Copy over simple attributes clone.info = deepcopy(context.info) clone.i18n_strings = deepcopy(context.i18n_strings) clone.package = deepcopy(context.package) clone.basepath = deepcopy(context.basepath) clone.includepath = deepcopy(context.includepath) clone._seen_files = deepcopy(context._seen_files) clone._features = deepcopy(context._features) try: clone.permission_mapping = deepcopy(context.permission_mapping) except AttributeError: pass # Note: We don't copy ``stack`` or ``actions`` since these are used during # ZCML file processing only # Copy over documentation registry clone._docRegistry = [tuple(list(entry))for entry in context._docRegistry] # Copy over the directive registry for key, registry in context._registry.items(): newRegistry = clone._registry.setdefault(key, AdapterRegistry()) for adapterRegistration in registry._adapters: if adapterRegistration not in newRegistry._adapters: for interface, info in adapterRegistration.items(): if Interface in info: factory = info[Interface][u''] newRegistry.register([interface], Interface, '', factory) logger.debug('Configuration context %s cloned from %s', clone, context) return clone
def testSetUp(cls, test=None): cls.context = ConfigurationMachine() registerCommonDirectives(cls.context) import transmogrifier xmlconfig.file('meta.zcml', transmogrifier, context=cls.context) xmlconfig.file('configure.zcml', transmogrifier, context=cls.context) cls.tempdir = tempfile.mkdtemp('transmogrifierTestConfigs')
def testSetUp(cls, test=None): cls.context = ConfigurationMachine() registerCommonDirectives(cls.context) import transmogrifier xmlconfig.file('meta.zcml', transmogrifier, context=cls.context) xmlconfig.file('configure.zcml', transmogrifier, context=cls.context) cls.tempdir = tempfile.mkdtemp('transmogrifierTestConfigs')
def _configure(self=None, set_up_packages=(), features=('devmode', 'testmode'), context=None, package=None): features = set(features) if features is not None else set() # This is normally created by a slug, but tests may not always # load the slug if os.getenv('DATASERVER_DIR_IS_BUILDOUT'): # pragma: no cover features.add('in-buildout') # zope.component.globalregistry conveniently adds # a zope.testing.cleanup.CleanUp to reset the globalSiteManager if context is None and (features or package): context = config.ConfigurationMachine() context.package = package xmlconfig.registerCommonDirectives(context) for feature in features: context.provideFeature(feature) if set_up_packages: logger.debug("Configuring %s with features %s", set_up_packages, features) for i in set_up_packages: __traceback_info__ = (i, self) if isinstance(i, tuple): filename = i[0] package = i[1] else: filename = 'configure.zcml' package = i if isinstance(package, six.string_types): package = dottedname.resolve(package) try: context = xmlconfig.file(filename, package=package, context=context) except IOError as e: # Did we pass in a test module (__name__) and there is no # configuration in that package? In that case, we want to # configure the parent package for sure module_path = getattr(package, '__file__', '') if (module_path and 'tests' in module_path and os.path.join(os.path.dirname(module_path), filename) == e.filename): parent_package_name = '.'.join(package.__name__.split('.')[:-2]) package = dottedname.resolve(parent_package_name) context = xmlconfig.file(filename, package=package, context=context) else: # pragma: no cover raise return context
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 test_w_empty_xml(self): from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.xmlconfig import ZopeSAXParseException from zope.configuration._compat import StringIO context = ConfigurationMachine() registerCommonDirectives(context) exc = self.assertRaises(ZopeSAXParseException, self._callFUT, StringIO(), context) self.assertEqual(str(exc._v), '<string>:1:0: no element found')
def setUp(self): # Previous test layer might be buggy and have left things # behind, so clear everything ourselves before doing setup # (like ZopeLite) layerCleanUp() # Set up this test layer. context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) self.context = self._load_zcml(context) provideHandler(events.append, (None,))
def zcml_configure(name, package): """ Given a ZCML filename as ``name`` and a Python package as ``package`` which the filename should be relative to, load the ZCML into the current ZCML registry. """ context = ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.package = package xmlconfig.include(context, name, package) context.execute_actions(clear=False) # the raison d'etre return context.actions
def test_w_empty_xml(self): from io import StringIO from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.xmlconfig import ZopeSAXParseException context = ConfigurationMachine() registerCommonDirectives(context) with self.assertRaises(ZopeSAXParseException) as exc: self._callFUT(StringIO(), context) self.assertEqual(str(exc.exception.evalue), '<string>:1:0: no element found')
def zcml_strings(dir, domain="zope", site_zcml=None): """Retrieve all ZCML messages from `dir` that are in the `domain`. """ from zope.configuration import xmlconfig, config # Load server-independent site config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.provideFeature("devmode") context = xmlconfig.file(site_zcml, context=context, execute=False) return context.i18n_strings.get(domain, {})
def test_w_empty_xml(self): from io import StringIO from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.xmlconfig import ZopeSAXParseException context = ConfigurationMachine() registerCommonDirectives(context) with self.assertRaises(ZopeSAXParseException) as exc: self._callFUT(StringIO(), context) self.assertEqual(str(exc.exception.evalue), '<string>:1:0: no element found')
def load_zcml(*args): """We rely on grok to load the configuration for our modules, but we depend on some libraries which have only zcml based configuration, thus we need to load only those we need.""" from zope.configuration.config import ConfigurationMachine from zope.configuration import xmlconfig context = ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for i in args: xmlconfig.include(context, "configure.zcml", context.resolve(i)) context.execute_actions()
def test_registry_actions_can_be_pickled_and_unpickled(self): import repoze.lemonade.tests.fixtureapp as package from zope.configuration import xmlconfig from zope.configuration import config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.package = package xmlconfig.include(context, 'configure.zcml', package) context.execute_actions(clear=False) actions = context.actions import cPickle dumped = cPickle.dumps(actions, -1) new = cPickle.loads(dumped) self.assertEqual(len(actions), len(new))
def test_actions_have_parents_includepath(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration import tests from zope.configuration.tests import simple context = ConfigurationMachine() fqp = _packageFile(tests, 'configure.zcml') registerCommonDirectives(context) before_stack = context.stack[:] context.package = tests # dummy action, path from "previous" include context.includepath = (fqp, ) def _callable(): pass context.actions.append({ 'discriminator': None, 'callable': _callable, }) fqn = _packageFile(tests, 'simple.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context, 'simple.zcml') self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s' % fqn, (), {})) self.assertEqual(len(context.actions), 4) action = context.actions[0] self.assertEqual(action['discriminator'], None) self.assertEqual(action['callable'], _callable) action = context.actions[1] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqp, )) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.py')) action = context.actions[2] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqp, )) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.zcml')) action = context.actions[3] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqp, )) self.assertEqual(action['args'][0].path, _packageFile(tests, '__init__.py')) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 1) self.assertIn(fqn, context._seen_files)
def xmlconfig(s, config=config): from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.xmlconfig import string context = ConfigurationMachine() context.autocommit = True context.registry = config.registry context.route_prefix = None context.actions = config.action_state.actions registerCommonDirectives(context) string(s, context=context, execute=False) config.commit()
def get_configuration_context(package=None): """Get configuration context. Various functions take a configuration context as argument. From looking at zope.configuration.xmlconfig.file the following seems about right. Note: this is a copy of a function in plone.autoinclude.tests.utils. The duplication is deliberate: I don't want one package to import code from the other, for now. """ context = ConfigurationMachine() registerCommonDirectives(context) if package is not None: # When you set context.package, context.path(filename) works nicely. context.package = package return context
def test_neither_file_nor_files_passed_already_seen(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage context = ConfigurationMachine() registerCommonDirectives(context) context.package = samplepackage fqn = _packageFile(samplepackage, 'configure.zcml') context._seen_files.add(fqn) logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context) #skips self.assertEqual(len(logger.debugs), 0) self.assertEqual(len(context.actions), 0)
def test_neither_file_nor_files_passed_already_seen(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage context = ConfigurationMachine() registerCommonDirectives(context) context.package = samplepackage fqn = _packageFile(samplepackage, 'configure.zcml') context._seen_files.add(fqn) logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context) #skips self.assertEqual(len(logger.debugs), 0) self.assertEqual(len(context.actions), 0)
def load_zcml(file, features=(), execute=True): r"""Execute the ZCML configuration file. This procedure defines the global site setup. Optionally you can also provide a list of features that are inserted in the configuration context before the execution is started. Let's create a trivial sample ZCML file. >>> import tempfile >>> fn = tempfile.mktemp('.zcml') >>> zcml = open(fn, 'w') >>> zcml.write(''' ... <configure xmlns:meta="http://namespaces.zope.org/meta" ... xmlns:zcml="http://namespaces.zope.org/zcml"> ... <meta:provides feature="myFeature" /> ... <configure zcml:condition="have myFeature2"> ... <meta:provides feature="myFeature4" /> ... </configure> ... </configure> ... ''') >>> zcml.close() We can now pass the file into the `load_zcml()` function: >>> context = load_zcml(fn, features=('myFeature2', 'myFeature3')) >>> context.hasFeature('myFeature') True >>> context.hasFeature('myFeature2') True >>> context.hasFeature('myFeature3') True >>> context.hasFeature('myFeature4') True Let's now clean up by removing the temporary file: >>> import os >>> os.remove(fn) """ # Load server-independent site config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in features: context.provideFeature(feature) context = xmlconfig.file(file, context=context, execute=execute) return context
def test_wo_execute_w_context(self): from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() registerCommonDirectives(context) file_name = path("samplepackage", "configure.zcml") with open(file_name) as f: xml = f.read() ret = self._callFUT(xml, context=context, execute=False) self.assertTrue(ret is context) self.assertEqual(len(foo.data), 0) self.assertEqual(len(context.actions), 1) action = context.actions[0] self.assertEqual(action['discriminator'], (('x', (b'blah')), ('y', 0))) self.assertEqual(action['callable'], foo.data.append)
def test_wo_execute_w_context(self): from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() registerCommonDirectives(context) file_name = path("samplepackage", "configure.zcml") with open(file_name) as f: xml = f.read() ret = self._callFUT(xml, context=context, execute=False) self.assertTrue(ret is context) self.assertEqual(len(foo.data), 0) self.assertEqual(len(context.actions), 1) action = context.actions[0] self.assertEqual(action['discriminator'], (('x', (b'blah')), ('y', 0))) self.assertEqual(action['callable'], foo.data.append)
def configure(options): from zope.error.error import globalErrorReportingUtility globalErrorReportingUtility.copy_to_zlog = True from zope.security.management import newInteraction, endInteraction endInteraction() newInteraction(SystemConfigurationParticipation()) zope.app.component.hooks.setHooks() from zope.configuration import xmlconfig, config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in options.features: context.provideFeature(feature) context = xmlconfig.string(options.site_definition, context=context) endInteraction()
def test_actions_have_parents_includepath(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration import tests from zope.configuration.tests import simple context = ConfigurationMachine() fqp = _packageFile(tests, 'configure.zcml') registerCommonDirectives(context) before_stack = context.stack[:] context.package = tests # dummy action, path from "previous" include context.includepath = (fqp,) def _callable(): raise AssertionError("should not be called") context.actions.append({'discriminator': None, 'callable': _callable, }) fqn = _packageFile(tests, 'simple.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context, 'simple.zcml') self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s', (fqn,), {})) self.assertEqual(len(context.actions), 4) action = context.actions[0] self.assertEqual(action['discriminator'], None) self.assertEqual(action['callable'], _callable) action = context.actions[1] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqp,)) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.py')) action = context.actions[2] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqp,)) self.assertEqual(action['args'][0].path, _packageFile(tests, 'simple.zcml')) action = context.actions[3] self.assertEqual(action['callable'], simple.file_registry.append) self.assertEqual(action['includepath'], (fqp,)) self.assertEqual(action['args'][0].path, _packageFile(tests, '__init__.py')) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 1) self.assertIn(fqn, context._seen_files)
def xmlconfig(s, config=config): from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.xmlconfig import string context = ConfigurationMachine() context.config_class = type(config) context.autocommit = True context.registry = config.registry context.route_prefix = None context.actions = config.action_state.actions context.introspection = False registerCommonDirectives(context) string(s, context=context, execute=False) config.commit()
def zcmlconfigure(settings): """ configuration for ZCML. The path to site.zcml must be written in the ini-file and defined in the section 'zcml' as 'path'. """ parser = configparser.ConfigParser() parser.read(settings.file) zcmlpath = parser.get("zcml", "path") # Hook up custom component architecture calls zope.component.hooks.setHooks() # Load server-independent site config context = zconfig.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context = xmlconfig.file(zcmlpath, context=context, execute=True) return context
def zcmlconfigure(settings): """ configuration for ZCML. The path to site.zcml must be written in the ini-file and defined in the section 'zcml' as 'path'. """ parser = configparser.ConfigParser() parser.read(settings.file) zcmlpath = parser.get('zcml', 'path') # Hook up custom component architecture calls zope.component.hooks.setHooks() # Load server-independent site config context = zconfig.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context = xmlconfig.file(zcmlpath, context=context, execute=True) return context
def test_nested_single_object_field_names_match_non_primitive_zcml(self): # The same as test_nested_single_object_field_names_match_non_primitive # but configured through ZCML using global objects. from zope.configuration import xmlconfig zcml = """ <configure xmlns:ext="http://nextthought.com/ntp/ext"> <include package="nti.externalization" file="meta.zcml" /> <ext:registerAutoPackageIO root_interfaces=".IGlobalNestedThing .IGlobalMiddleThing .IGlobalRoot" iobase=".IOBase" modules="{0}" /> <ext:anonymousObjectFactory for=".IGlobalRoot" field="field" factory=".GlobalMiddleThing" /> <ext:anonymousObjectFactory for=".IGlobalMiddleThing" field="nested" factory=".GlobalNestedThing" /> </configure> """.format(__name__) context = xmlconfig.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.package = sys.modules[__name__] xmlconfig.string(zcml, context) external = {'field': {'nested': {'value': 42}, 'nested_dict': {'key': {'value': 24}}}} root = GlobalRoot() update_from_external_object(root, external, require_updater=True) assert_that(root, has_attr('field', is_(GlobalMiddleThing))) assert_that(root.field, has_attr('nested', is_(GlobalNestedThing))) assert_that(root.field, has_attr('nested', has_attr('value', 42)))
def test_w_valid_xml_fp(self): # Integration test, really from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration._compat import b from zope.configuration.tests.samplepackage import foo file = open(path("samplepackage", "configure.zcml")) context = ConfigurationMachine() registerCommonDirectives(context) self._callFUT(file, context) self.assertEqual(foo.data, []) context.execute_actions() data = foo.data.pop() self.assertEqual(data.args, (('x', b('blah')), ('y', 0))) self.assertEqual(clean_info_path(repr(data.info)), 'File "tests/samplepackage/configure.zcml", line 12.2-12.29') self.assertEqual(clean_info_path(str(data.info)), 'File "tests/samplepackage/configure.zcml", line 12.2-12.29\n' + ' <test:foo x="blah" y="0" />') self.assertEqual(data.package, None) self.assertEqual(data.basepath, None)
def test_w_valid_xml_fp(self): # Integration test, really from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration._compat import b from zope.configuration.tests.samplepackage import foo file = open(path("samplepackage", "configure.zcml")) context = ConfigurationMachine() registerCommonDirectives(context) self._callFUT(file, context) self.assertEqual(foo.data, []) context.execute_actions() data = foo.data.pop() self.assertEqual(data.args, (('x', b('blah')), ('y', 0))) self.assertEqual(clean_info_path(repr(data.info)), 'File "tests/samplepackage/configure.zcml", line 12.2-12.29') self.assertEqual(clean_info_path(str(data.info)), 'File "tests/samplepackage/configure.zcml", line 12.2-12.29\n' + ' <test:foo x="blah" y="0" />') self.assertEqual(data.package, None) self.assertEqual(data.basepath, None)
def configure(options): from zope.error.error import globalErrorReportingUtility globalErrorReportingUtility.copy_to_zlog = True from zope.security.management import newInteraction, endInteraction endInteraction() newInteraction(SystemConfigurationParticipation()) zope.app.component.hooks.setHooks() from zope.configuration import xmlconfig, config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in options.features: context.provideFeature(feature) with warnings.catch_warnings(): # zope.app.security globalmodules.zcml declares security directives for # some modules deprecated in newer versions of Python. warnings.filterwarnings('ignore', message='^the formatter module is deprecated') context = xmlconfig.string(options.site_definition, context=context) endInteraction()
def configure(options): from zope.error.error import globalErrorReportingUtility globalErrorReportingUtility.copy_to_zlog = True from zope.security.management import newInteraction, endInteraction endInteraction() newInteraction(SystemConfigurationParticipation()) zope.app.component.hooks.setHooks() from zope.configuration import xmlconfig, config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) for feature in options.features: context.provideFeature(feature) with warnings.catch_warnings(): # zope.app.security globalmodules.zcml declares security directives for # some modules deprecated in newer versions of Python. warnings.filterwarnings('ignore', message='^the formatter module is deprecated') context = xmlconfig.string(options.site_definition, context=context) endInteraction()
def sectionsSetUp(test): setUp(test) from collective.transmogrifier.transmogrifier import Transmogrifier test.globs['transmogrifier'] = Transmogrifier(test.globs['plone']) import collective.transmogrifier.sections context = ConfigurationMachine() registerCommonDirectives(context) xmlconfig.file('testing.zcml', collective.transmogrifier.sections, context=context) context.execute_actions() provideUtility(SampleSource, name=u'collective.transmogrifier.sections.tests.samplesource') provideUtility(RangeSource, name=u'collective.transmogrifier.sections.tests.rangesource') import logging from zope.testing import loggingsupport test.globs['handler'] = loggingsupport.InstalledHandler( 'logger', level=logging.INFO)
def zcml(source): context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) # Test directives config.defineSimpleDirective(context, "print", IPrint, print_, namespace="*") config.defineSimpleDirective(context, "lolcat", ILolCat, lolcat, namespace="*") source = '''\ <configure package="z3c.unconfigure.tests.fixtures"> %s </configure>''' % source xmlconfig.string(source, context)
def test_neither_file_nor_files_passed(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() registerCommonDirectives(context) before_stack = context.stack[:] context.package = samplepackage fqn = _packageFile(samplepackage, 'configure.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context) self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s', (fqn,), {})) self.assertEqual(len(context.actions), 1) action = context.actions[0] self.assertEqual(action['callable'], foo.data.append) self.assertEqual(action['includepath'], (fqn,)) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 1) self.assertIn(fqn, context._seen_files)
def test_wo_execute_w_context(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() context.package = samplepackage registerCommonDirectives(context) file_name = path("samplepackage", "configure.zcml") logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): ret = self._callFUT('configure.zcml', context=context, execute=False) self.assertTrue(ret is context) self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s', (file_name,), {})) self.assertEqual(len(foo.data), 0) self.assertEqual(len(context.actions), 1) action = context.actions[0] self.assertEqual(action['discriminator'], (('x', (b'blah')), ('y', 0))) self.assertEqual(action['callable'], foo.data.append)
def test_wo_execute_w_context(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() context.package = samplepackage registerCommonDirectives(context) file_name = path("samplepackage", "configure.zcml") logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): ret = self._callFUT('configure.zcml', context=context, execute=False) self.assertTrue(ret is context) self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s', (file_name, ), {})) self.assertEqual(len(foo.data), 0) self.assertEqual(len(context.actions), 1) action = context.actions[0] self.assertEqual(action['discriminator'], (('x', (b'blah')), ('y', 0))) self.assertEqual(action['callable'], foo.data.append)
def test_neither_file_nor_files_passed(self): from zope.configuration import xmlconfig from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives from zope.configuration.tests import samplepackage from zope.configuration.tests.samplepackage import foo context = ConfigurationMachine() registerCommonDirectives(context) before_stack = context.stack[:] context.package = samplepackage fqn = _packageFile(samplepackage, 'configure.zcml') logger = LoggerStub() with _Monkey(xmlconfig, logger=logger): self._callFUT(context) self.assertEqual(len(logger.debugs), 1) self.assertEqual(logger.debugs[0], ('include %s' % fqn, (), {})) self.assertEqual(len(context.actions), 1) action = context.actions[0] self.assertEqual(action['callable'], foo.data.append) self.assertEqual(action['includepath'], (fqn, )) self.assertEqual(context.stack, before_stack) self.assertEqual(len(context._seen_files), 1) self.assertIn(fqn, context._seen_files)
def zcml_strings(path, domain="zope", site_zcml=None): """Retrieve all ZCML messages from `dir` that are in the `domain`. Note, the pot maker runs in a loop for each package and the maker collects only the given messages from such a package by the given path. This allows us to collect messages from eggs and external packages. This also prevents to collect the same message more then one time since we use the same zcml configuration for each package path. """ from zope.configuration import xmlconfig, config # The context will return the domain as an 8-bit character string. if not isinstance(domain, bytes): domain = domain.encode('ascii') # Load server-independent site config context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.provideFeature("devmode") context = xmlconfig.file(site_zcml, context=context, execute=False) catalog = context.i18n_strings.get(domain, {}) res = {} duplicated = [] append = duplicated.append for msg, locations in catalog.items(): for filename, lineno in locations: # only collect locations based on the given path if filename.startswith(path): id = '%s-%s-%s' % (msg, filename, lineno) # skip duplicated entries if id not in duplicated: append(id) l = res.get(msg, []) l.append((filename, lineno)) res[msg] = l return res
def load_zcml(self, spec='configure.zcml', lock=threading.Lock(), features=()): """ Load configuration from a :term:`ZCML` file into the current configuration state. The ``spec`` argument is an absolute filename, a relative filename, or a :term:`asset specification`, defaulting to ``configure.zcml`` (relative to the package of the method's caller). The ``features`` argument can be any iterable of strings. These are useful for conditionally including or excluding parts of a :term:`ZCML` file. """ package_name, filename = self._split_spec(spec) if package_name is None: # absolute filename package = self.package else: __import__(package_name) package = sys.modules[package_name] # To avoid breaking people's expectations of how ZCML works, we # cannot autocommit ZCML actions incrementally. If we commit actions # incrementally, configuration outcome will be controlled purely by # ZCML directive execution order, which isn't what anyone who uses # ZCML expects. So we don't autocommit each ZCML directive action # while parsing is happening, but we do make sure to commit right # after parsing if autocommit it True. context = ConfigurationMachine() for feature in features: context.provideFeature(feature) context.registry = self.registry context.autocommit = False context.package = package context.route_prefix = getattr(self, 'route_prefix', None) context.introspection = getattr(self, 'introspection', True) context.config_class = self.__class__ registerCommonDirectives(context) self.manager.push({'registry': self.registry, 'request': None}) lock.acquire() try: # old_action_state will be None for Pyramid 1.0 and 1.1, but # not for 1.2 old_action_state = getattr(self.registry, 'action_state', None) if old_action_state is not None: # For Pyramid 1.2+, we need to assign a temporary action state to # the registry, because the configurator actions must populate # the context's action list (instead of the registry action # state's action list) in order for includeOverrides to work # properly. from pyramid.config import ActionState self.registry.action_state = ActionState() self.registry.action_state.actions = context.actions xmlconfig.file(filename, package, context=context, execute=False) finally: if old_action_state is not None: # if we reassigned the action state, restore the old one (1.2 only) self.registry.action_state = old_action_state lock.release() self.manager.pop() self._ctx.actions.extend(context.actions) if self.autocommit: self.commit() return self.registry
def zcml(source): context = config.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) xmlconfig.string(source, context)
def execute_zcml_for_scripts(use_web_security=False): """Execute the zcml rooted at launchpad/script.zcml If use_web_security is True, the same security policy as the web application uses will be used. Otherwise everything protected by a permission is allowed, and everything else denied. """ # When in testing mode, prevent some cases of erroneous layer usage. # But we don't want to import that module in production usage, thus # the conditional block. if 'lp.testing.layers' in sys.modules: from lp.testing.layers import (FunctionalLayer, BaseLayer, ZopelessLayer) assert not FunctionalLayer.isSetUp, \ 'Setting up Zopeless CA when Zopefull CA is already running' assert not BaseLayer.isSetUp or ZopelessLayer.isSetUp, """ execute_zcml_for_scripts should not be called from tests. Instead, your test should use the Zopeless layer. """ if config.isTestRunner(): scriptzcmlfilename = 'script-testing.zcml' else: scriptzcmlfilename = 'script.zcml' scriptzcmlfilename = os.path.abspath( os.path.join(config.root, 'zcml', scriptzcmlfilename)) from zope.configuration import xmlconfig # Hook up custom component architecture calls zope.site.hooks.setHooks() # Load server-independent site config context = ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context = xmlconfig.file(scriptzcmlfilename, execute=True, context=context) if use_web_security: setSecurityPolicy(LaunchpadSecurityPolicy) else: setSecurityPolicy(LaunchpadPermissiveSecurityPolicy) # Register atexit handler to kill off mail delivery daemon threads, and # thus avoid spew at exit. See: # http://mail.python.org/pipermail/python-list/2003-October/192044.html # http://mail.python.org/pipermail/python-dev/2003-September/038151.html # http://mail.python.org/pipermail/python-dev/2003-September/038153.html def kill_queue_processor_threads(): for thread in threading.enumerate(): if isinstance(thread, zope.sendmail.delivery.QueueProcessorThread): thread.stop() thread.join(30) if thread.isAlive(): raise RuntimeError( "QueueProcessorThread did not shut down") atexit.register(kill_queue_processor_threads) # This is a convenient hack to set up a zope interaction, before we get # the proper API for having a principal / user running in scripts. setupInteractionByEmail(ANONYMOUS)
def make_app(config_file=None, settings=None): app_settings.update(_delayed_default_settings) # Initialize aiohttp app app = web.Application(router=TraversalRouter()) # Create root Application root = ApplicationRoot(config_file) root.app = app provideUtility(root, IApplication, 'root') # Initialize global (threadlocal) ZCA configuration app.config = ConfigurationMachine() registerCommonDirectives(app.config) if config_file is not None: with open(config_file, 'r') as config: settings = json.load(config) elif settings is None: raise Exception('Neither configuration or settings') import plone.server configure.include("zope.component") configure.include("zope.annotation") configure.include("plone.server", "meta.zcml") # bbb configure.scan('plone.server.translation') configure.scan('plone.server.renderers') configure.scan('plone.server.api') configure.scan('plone.server.content') configure.scan('plone.server.security') configure.scan('plone.server.json') configure.scan('plone.server.behaviors') configure.scan('plone.server.languages') configure.scan('plone.server.permissions') configure.scan('plone.server.migrate.migrations') configure.scan('plone.server.auth.participation') configure.scan('plone.server.auth.principalrole') configure.scan('plone.server.catalog.index') configure.scan('plone.server.catalog.catalog') configure.scan('plone.server.framing') configure.scan('plone.server.file') configure.scan('plone.server.types') load_application(plone.server, root, settings) for ep in iter_entry_points('plone.server'): # auto-include applications # What an "app" include consists of... # 1. load zcml if present # 2. load "includeme" module function if present # 3. load app_settings dict if present in the module if ep.module_name not in settings.get('applications', []): continue load_application(ep.load(), root, settings) try: app.config.execute_actions() except ConfigurationConflictError as e: logger.error(str(e._conflicts)) raise e # XXX we clear now to save some memory # it's unclear to me if this is necesary or not but it seems to me that # we don't need things registered in both components AND here. configure.clear() # update *after* plugins loaded update_app_settings(settings) content_type = ContentNegotiatorUtility( 'content_type', app_settings['renderers'].keys()) language = ContentNegotiatorUtility( 'language', app_settings['languages'].keys()) provideUtility(content_type, IContentNegotiation, 'content_type') provideUtility(language, IContentNegotiation, 'language') for database in app_settings['databases']: for key, dbconfig in database.items(): factory = getUtility( IDatabaseConfigurationFactory, name=dbconfig['storage']) root[key] = factory(key, dbconfig) for static in app_settings['static']: for key, file_path in static.items(): root[key] = StaticFile(file_path) root.set_root_user(app_settings['root_user']) if RSA is not None and not app_settings.get('rsa'): key = RSA.generate(2048) pub_jwk = {'k': key.publickey().exportKey('PEM')} priv_jwk = {'k': key.exportKey('PEM')} app_settings['rsa'] = { 'pub': pub_jwk, 'priv': priv_jwk } # Set router root app.router.set_root(root) for utility in getAllUtilitiesRegisteredFor(IAsyncUtility): # In case there is Utilties that are registered from zcml ident = asyncio.ensure_future(utility.initialize(app=app), loop=app.loop) root.add_async_utility(ident, {}) app.on_cleanup.append(close_utilities) for util in app_settings['utilities']: root.add_async_utility(util) # Load cached Schemas load_cached_schema() return app
module is not excluded: >>> xmlconfig.string(''' ... <configure xmlns:grok="http://namespaces.zope.org/grok"> ... <include package="grokcore.component" file="meta.zcml"/> ... <grok:grok package="." /> ... </configure>''', context) Traceback (most recent call last): ZopeXMLConfigurationError: File "<string>", line 4.6-4.31 NameError: name 'asdf' is not defined Excluding `.excludepkg.sample` via ZCML allows to successfully grok the module: >>> xmlconfig.string(''' ... <configure xmlns:grok="http://namespaces.zope.org/grok"> ... <include package="grokcore.component" file="meta.zcml"/> ... <grok:grok package="." ... exclude="sample" /> ... </configure>''', context) <zope.configuration.config.ConfigurationMachine ...> """ from zope.configuration import xmlconfig from grokcore.component.tests.zcml import excludepkg context = xmlconfig.ConfigurationMachine() xmlconfig.registerCommonDirectives(context) context.package = excludepkg