示例#1
0
def register_test_entry_point():
    test_resource_file = os.path.abspath(
        os.path.join(os.path.dirname(__file__), 'resources/entry_points.py'))
    distribution = pkg_resources.Distribution.from_filename(test_resource_file)
    entry_point = pkg_resources.EntryPoint(
        'foo', 'ospurge.tests.resources.entry_points', dist=distribution)
    distribution._ep_map = {utils.ENTRY_POINTS_NAME: {'foo': entry_point}}
    pkg_resources.working_set.add(distribution, 'foo')
    return entry_point
示例#2
0
 def setUp(self):
     self.plugin_ep = mock.MagicMock()
     self.plugin_ep.name = "mock"
     self.plugin_ep.__hash__.side_effect = TypeError
     self.plugins = {self.plugin_ep.name: self.plugin_ep}
     self.reg = self._create_new_registry(self.plugins)
     self.ep1 = pkg_resources.EntryPoint("ep1",
                                         "p1.ep1",
                                         dist=mock.MagicMock(key="p1"))
示例#3
0
    def setUp(self):
        self.ep1 = pkg_resources.EntryPoint("ep1",
                                            "p1.ep1",
                                            dist=mock.MagicMock(key="p1"))
        self.ep1prim = pkg_resources.EntryPoint("ep1",
                                                "p2.ep2",
                                                dist=mock.MagicMock(key="p2"))
        # nested
        self.ep2 = pkg_resources.EntryPoint("ep2",
                                            "p2.foo.ep2",
                                            dist=mock.MagicMock(key="p2"))
        # project name != top-level package name
        self.ep3 = pkg_resources.EntryPoint("ep3",
                                            "a.ep3",
                                            dist=mock.MagicMock(key="p3"))

        from certbot.plugins.disco import PluginEntryPoint
        self.plugin_ep = PluginEntryPoint(EP_SA)
示例#4
0
    def test_generate_script_validates_expectations(self):
        group = 'console_scripts'
        entry_point = pkg_resources.EntryPoint(
            name='test-ep',
            module_name='pbr.packaging')
        header = '#!/usr/bin/env fake-header\n'
        template = ('%(group)s %(module_name)s %(import_target)s '
                    '%(invoke_target)s')
        self.assertRaises(
            ValueError, packaging.generate_script, group, entry_point, header,
            template)

        entry_point = pkg_resources.EntryPoint(
            name='test-ep',
            module_name='pbr.packaging',
            attrs=('attr1', 'attr2', 'attr3'))
        self.assertRaises(
            ValueError, packaging.generate_script, group, entry_point, header,
            template)
示例#5
0
def default_entry_point():
    """
    Return a default orange.widgets entry point for loading
    default Orange Widgets.

    """
    dist = pkg_resources.get_distribution("Orange3")
    ep = pkg_resources.EntryPoint("Orange Widgets", "Orange.widgets",
                                  dist=dist)
    return ep
示例#6
0
    def widgets_entry_points():
        """
        Return an `EntryPoint` iterator for all 'orange.widget' entry
        points plus the default Orange Widgets.

        """
        dist = pkg_resources.get_distribution("Orange")
        ep = pkg_resources.EntryPoint("Orange Widgets", "Orange.widgets",
                                      dist=dist)
        return iter((ep,) +
                    tuple(pkg_resources.iter_entry_points(WIDGETS_ENTRY)))
示例#7
0
    def test_examples_order(self):
        # register test entrypoints
        dist_orange = pkg_resources.working_set.by_key['orange3']
        ep_map = dist_orange.get_entry_map()
        ep_first = pkg_resources.EntryPoint(
            '!Testname', 'orangecontrib.any_addon.tutorials')
        ep_last = pkg_resources.EntryPoint(
            'exampletutorials', 'orangecontrib.other_addon.tutorials')
        ep_map['orange.widgets.tutorials'] = {
            ep_first.name: ep_first,
            ep_last.name: ep_last
        }

        ep_names = [point.name for point in Config.examples_entry_points()]
        self.assertLess(ep_names.index(ep_first.name),
                        ep_names.index("000-Orange3"))
        self.assertLess(ep_names.index("000-Orange3"),
                        ep_names.index(ep_last.name))

        del ep_map['orange.widgets.tutorials']
示例#8
0
    def test_entrypoint_tolerance(self):
        # loosely based on Pandas test from:
        #   https://github.com/pandas-dev/pandas/pull/27488

        # FIXME: Python 2 workaround because nonlocal doesn't exist
        counters = {"init": 0}

        def init_function():
            counters["init"] += 1
            raise ValueError("broken")

        mod = types.ModuleType("_test_numba_bad_extension")
        mod.init_func = init_function

        try:
            # will remove this module at the end of the test
            sys.modules[mod.__name__] = mod

            # We are registering an entry point using the "numba" package
            # ("distribution" in pkg_resources-speak) itself, though these are
            # normally registered by other packages.
            dist = "numba"
            entrypoints = pkg_resources.get_entry_map(dist)
            my_entrypoint = pkg_resources.EntryPoint(
                "init",  # name of entry point
                mod.__name__,  # module with entry point object
                attrs=["init_func"],  # name of entry point object
                dist=pkg_resources.get_distribution(dist),
            )
            entrypoints.setdefault("numba_extensions", {})["init"] = my_entrypoint

            from numba.core import entrypoints

            # Allow reinitialization
            entrypoints._already_initialized = False

            with warnings.catch_warnings(record=True) as w:
                entrypoints.init_all()

            bad_str = "Numba extension module '_test_numba_bad_extension'"
            for x in w:
                if bad_str in str(x):
                    break
            else:
                raise ValueError("Expected warning message not found")

            # was our init function called?
            self.assertEqual(counters["init"], 1)

        finally:
            # remove fake module
            if mod.__name__ in sys.modules:
                del sys.modules[mod.__name__]
示例#9
0
def test_get_versions_with_plugins(monkeypatch):
    import nose
    import pkg_resources
    monkeypatch.setattr(nose, '__version__', '1.2.3')
    dist = pkg_resources.Distribution(project_name='myPlugin', version='4.5.6')
    ep = pkg_resources.EntryPoint('name', 'module_name', dist=dist)
    monkeypatch.setattr(
        pkg_resources, 'iter_entry_points', lambda ept:
        (x for x in (ep, ) if ept == nose.plugins.manager.
         EntryPointPluginManager.entry_points[0][0]))
    runner = NoseRunner(None)
    assert runner.get_versions() == ['nose 1.2.3', '   myPlugin 4.5.6']
示例#10
0
    def examples_entry_points():
        # type: () -> Iterable[pkg_resources.EntryPoint]
        """
        Return an iterator over the entry points yielding 'Example Workflows'
        """
        # `iter_entry_points` yields them in unspecified order, so we insert
        # our first
        try:
            default_ep = pkg_resources.EntryPoint(
                "Orange3",
                "Orange.canvas.workflows",
                dist=pkg_resources.get_distribution("Orange3-zh"))
        except pkg_resources.DistributionNotFound:
            default_ep = pkg_resources.EntryPoint(
                "Orange3",
                "Orange.canvas.workflows",
                dist=pkg_resources.get_distribution("Orange3"))

        return itertools.chain(
            (default_ep, ),
            pkg_resources.iter_entry_points("orange.widgets.tutorials"))
示例#11
0
    def setup(self):
        dist = pkg_resources.get_distribution("pandas")
        spec = importlib.machinery.ModuleSpec("my_backend", None)
        mod = importlib.util.module_from_spec(spec)
        mod.plot = lambda *args, **kwargs: 1

        backends = pkg_resources.get_entry_map("pandas")
        my_entrypoint = pkg_resources.EntryPoint("pandas_plotting_backend",
                                                 mod.__name__,
                                                 dist=dist)
        backends["pandas_plotting_backends"][mod.__name__] = my_entrypoint
        for i in range(10):
            backends["pandas_plotting_backends"][str(i)] = my_entrypoint
        sys.modules["my_backend"] = mod
示例#12
0
def test_entrypoint_tolerance():
    # FIXME: Python 2 workaround because nonlocal doesn't exist
    counters = {"init": 0}

    def init_function():
        counters["init"] += 1
        raise ValueError("broken")

    mod = types.ModuleType("_test_mars_bad_extension")
    mod.init_func = init_function

    try:
        # will remove this module at the end of the test
        sys.modules[mod.__name__] = mod

        # We are registering an entry point using the "mars" package
        # ("distribution" in pkg_resources-speak) itself, though these are
        # normally registered by other packages.
        dist = "pymars"
        entrypoints = pkg_resources.get_entry_map(dist)
        my_entrypoint = pkg_resources.EntryPoint(
            "init",  # name of entry point
            mod.__name__,  # module with entry point object
            attrs=["init_func"],  # name of entry point object
            dist=pkg_resources.get_distribution(dist),
        )
        entrypoints.setdefault("mars_extensions", {})["init"] = my_entrypoint

        from .. import entrypoints

        # Allow reinitialization
        entrypoints.init_extension_entrypoints.cache_clear()

        with warnings.catch_warnings(record=True) as w:
            entrypoints.init_extension_entrypoints()

        bad_str = "Mars extension module '_test_mars_bad_extension'"
        for x in w:
            if bad_str in str(x):
                break
        else:
            raise ValueError("Expected warning message not found")

        # was our init function called?
        assert counters["init"] == 1

    finally:
        # remove fake module
        if mod.__name__ in sys.modules:
            del sys.modules[mod.__name__]
示例#13
0
    def test_generate_script(self):
        group = 'console_scripts'
        entry_point = pkg_resources.EntryPoint(name='test-ep',
                                               module_name='pbr.packaging',
                                               attrs=('LocalInstallScripts', ))
        header = '#!/usr/bin/env fake-header\n'
        template = ('%(group)s %(module_name)s %(import_target)s '
                    '%(invoke_target)s')

        generated_script = packaging.generate_script(group, entry_point,
                                                     header, template)

        expected_script = (
            '#!/usr/bin/env fake-header\nconsole_scripts pbr.packaging '
            'LocalInstallScripts LocalInstallScripts')
        self.assertEqual(expected_script, generated_script)
示例#14
0
    def test_init_entrypoint(self):
        # loosely based on Pandas test from:
        #   https://github.com/pandas-dev/pandas/pull/27488

        # FIXME: Python 2 workaround because nonlocal doesn't exist
        counters = {'init': 0}

        def init_function():
            counters['init'] += 1

        mod = types.ModuleType("_test_numba_extension")
        mod.init_func = init_function

        try:
            # will remove this module at the end of the test
            sys.modules[mod.__name__] = mod

            # We are registering an entry point using the "numba" package
            # ("distribution" in pkg_resources-speak) itself, though these are
            # normally registered by other packages.
            dist = "numba"
            entrypoints = pkg_resources.get_entry_map(dist)
            my_entrypoint = pkg_resources.EntryPoint(
                "init", # name of entry point
                mod.__name__, # module with entry point object
                attrs=['init_func'], # name of entry point object
                dist=pkg_resources.get_distribution(dist)
            )
            entrypoints.setdefault('numba_extensions',
                                   {})['init'] = my_entrypoint

            import numba.entrypoints
            # Allow reinitialization
            numba.entrypoints._already_initialized = False

            numba.entrypoints.init_all()

            # was our init function called?
            self.assertEqual(counters['init'], 1)

            # ensure we do not initialize twice
            numba.entrypoints.init_all()
            self.assertEqual(counters['init'], 1)
        finally:
            # remove fake module
            if mod.__name__ in sys.modules:
                del sys.modules[mod.__name__]
示例#15
0
    def examples_entry_points():
        # type: () -> Iterable[pkg_resources.EntryPoint]
        """
        Return an iterator over the entry points yielding 'Example Workflows'
        """
        # `iter_entry_points` yields them in unspecified order, so we order
        # them by name. The default is at the beginning, unless another
        # entrypoint precedes it alphabetically (e.g. starting with '!').
        default_ep = pkg_resources.EntryPoint(
            "000-Orange3",
            "Orange.canvas.workflows",
            dist=pkg_resources.get_distribution("Orange3"))

        all_ep = list(
            pkg_resources.iter_entry_points("orange.widgets.tutorials"))
        all_ep.append(default_ep)
        all_ep.sort(key=lambda x: x.name)
        return iter(all_ep)
示例#16
0
def test_init_entrypoint():
    # FIXME: Python 2 workaround because nonlocal doesn't exist
    counters = {"init": 0}

    def init_function():
        counters["init"] += 1

    mod = types.ModuleType("_test_mars_extension")
    mod.init_func = init_function

    try:
        # will remove this module at the end of the test
        sys.modules[mod.__name__] = mod

        # We are registering an entry point using the "mars" package
        # ("distribution" in pkg_resources-speak) itself, though these are
        # normally registered by other packages.
        dist = "pymars"
        entrypoints = pkg_resources.get_entry_map(dist)
        my_entrypoint = pkg_resources.EntryPoint(
            "init",  # name of entry point
            mod.__name__,  # module with entry point object
            attrs=["init_func"],  # name of entry point object
            dist=pkg_resources.get_distribution(dist),
        )
        entrypoints.setdefault("mars_extensions", {})["init"] = my_entrypoint

        from .. import entrypoints

        # Allow reinitialization
        entrypoints.init_extension_entrypoints.cache_clear()

        entrypoints.init_extension_entrypoints()

        # was our init function called?
        assert counters["init"] == 1

        # ensure we do not initialize twice
        entrypoints.init_extension_entrypoints()
        assert counters["init"] == 1
    finally:
        # remove fake module
        if mod.__name__ in sys.modules:
            del sys.modules[mod.__name__]
示例#17
0
    def test_import_module_from_entrypoint(self):

        config = {}
        config["module_path"] = ""
        config["name"] = "myep"
        config["type"] = ""
        config["module"] = ""

        distro = pkg_resources.Distribution()
        ep = pkg_resources.EntryPoint("myep", "os.path", dist=distro)
        config["entrypoint"] = ep

        opsdroid, loader = self.setup()
        loader.modules_directory = "."
        modules = {"myep": {}}

        with mock.patch("opsdroid.loader.iter_entry_points") as mock_iter_entry_points:
            mock_iter_entry_points.return_value = (ep,)
            loaded = loader._load_modules("database", modules)
            self.assertEqual(loaded[0]["config"]["name"], "myep")
示例#18
0
def test_get_label_entrypoint(plugin_tmpfile):
    # generate setuptools Distribution object
    distrib_dir = os.path.dirname(plugin_tmpfile.strpath)
    distrib = pkg_resources.Distribution(distrib_dir)
    sys.path.append(distrib_dir)

    # load the entry point
    try:
        entry_point = pkg_resources.EntryPoint(
            'test_plugin', 'file_mod', dist=distrib)
        plugin = handlers.EntryPointPlugin(entry_point)
        plugin.load()
    finally:
        sys.path.remove(distrib_dir)

    meta = plugin.get_meta_description()
    assert meta['name'] == 'test_plugin'
    assert meta['label'] == 'module label'
    assert meta['type'] == handlers.EntryPointPlugin.PLUGIN_TYPE
    assert meta['source'] == 'test_plugin = file_mod'
示例#19
0
def test_register_backend_entrypoint():
    # Code adapted from pandas backend entry point testing
    # https://github.com/pandas-dev/pandas/blob/2470690b9f0826a8feb426927694fa3500c3e8d2/pandas/tests/plotting/test_backend.py#L50-L76

    dist = pkg_resources.get_distribution("distributed")
    if dist.module_path not in distributed.__file__:
        # We are running from a non-installed distributed, and this test is invalid
        pytest.skip("Testing a non-installed distributed")

    mod = types.ModuleType("dask_udp")
    mod.UDPBackend = lambda: 1
    sys.modules[mod.__name__] = mod

    entry_point_name = "distributed.comm.backends"
    backends_entry_map = pkg_resources.get_entry_map("distributed")
    if entry_point_name not in backends_entry_map:
        backends_entry_map[entry_point_name] = dict()
    backends_entry_map[entry_point_name]["udp"] = pkg_resources.EntryPoint(
        "udp", mod.__name__, attrs=["UDPBackend"], dist=dist)

    result = get_backend("udp")
    assert result == 1
示例#20
0
def test_find_importers_through_entry_points(mocker):
    from passpie import importers

    temp_dir = tempfile.mkdtemp()
    sys.path.insert(0, temp_dir)

    with open(os.path.join(temp_dir, 'fake_module.py'), 'w') as f:
        f.write("""\
from passpie.importers import BaseImporter

class FakeKeepassImporterClass(BaseImporter):
    pass
""")

    import pkg_resources
    fake_ep = pkg_resources.EntryPoint('fake_keepass',
                                       'fake_module',
                                       attrs=('FakeKeepassImporterClass', ))
    mock_iter_entry_points = mocker.patch('pkg_resources.iter_entry_points',
                                          return_value=iter([
                                              fake_ep,
                                          ]))

    try:
        target_klass = None
        for klass in importers._get_importers_from_entry_points():
            if klass.__name__ == 'FakeKeepassImporterClass':
                target_klass = klass
                break

        mock_iter_entry_points.assert_called_once_with('passpie_importers')

        assert target_klass.__name__ == 'FakeKeepassImporterClass'
        assert target_klass.__module__ == 'fake_module'

    finally:
        sys.path.remove(temp_dir)
        shutil.rmtree(temp_dir, ignore_errors=True)
示例#21
0
def test_register_entrypoint():
    mod = types.ModuleType("my_backend")
    mod.plot = lambda *args, **kwargs: 1

    backends = pkg_resources.get_entry_map("pandas")
    my_entrypoint = pkg_resources.EntryPoint(
        "pandas_plotting_backend",
        mod.__name__,
        dist=pkg_resources.get_distribution("pandas"),
    )
    backends["pandas_plotting_backends"]["my_backend"] = my_entrypoint
    # TODO: the docs recommend importlib.util.module_from_spec. But this works for now.
    sys.modules["my_backend"] = mod

    result = pandas.plotting._core._get_plot_backend("my_backend")
    assert result is mod

    # TODO: https://github.com/pandas-dev/pandas/issues/27517
    # Remove the td.skip_if_no_mpl
    with pandas.option_context("plotting.backend", "my_backend"):
        result = pandas.plotting._core._get_plot_backend()

    assert result is mod
示例#22
0
    def __init__(self,
                 cloud=None,
                 config=None,
                 session=None,
                 app_name=None,
                 app_version=None,
                 extra_services=None,
                 strict=False,
                 use_direct_get=False,
                 task_manager=None,
                 rate_limit=None,
                 oslo_conf=None,
                 service_types=None,
                 global_request_id=None,
                 strict_proxies=False,
                 **kwargs):
        """Create a connection to a cloud.

        A connection needs information about how to connect, how to
        authenticate and how to select the appropriate services to use.

        The recommended way to provide this information is by referencing
        a named cloud config from an existing `clouds.yaml` file. The cloud
        name ``envvars`` may be used to consume a cloud configured via ``OS_``
        environment variables.

        A pre-existing :class:`~openstack.config.cloud_region.CloudRegion`
        object can be passed in lieu of a cloud name, for cases where the user
        already has a fully formed CloudRegion and just wants to use it.

        Similarly, if for some reason the user already has a
        :class:`~keystoneauth1.session.Session` and wants to use it, it may be
        passed in.

        :param str cloud: Name of the cloud from config to use.
        :param config: CloudRegion object representing the config for the
            region of the cloud in question.
        :type config: :class:`~openstack.config.cloud_region.CloudRegion`
        :param session: A session object compatible with
            :class:`~keystoneauth1.session.Session`.
        :type session: :class:`~keystoneauth1.session.Session`
        :param str app_name: Name of the application to be added to User Agent.
        :param str app_version: Version of the application to be added to
            User Agent.
        :param extra_services: List of
            :class:`~openstack.service_description.ServiceDescription`
            objects describing services that openstacksdk otherwise does not
            know about.
        :param bool use_direct_get:
            For get methods, make specific REST calls for server-side
            filtering instead of making list calls and filtering client-side.
            Default false.
        :param task_manager:
            Ignored. Exists for backwards compat during transition. Rate limit
            parameters should be passed directly to the `rate_limit` parameter.
        :param rate_limit:
            Client-side rate limit, expressed in calls per second. The
            parameter can either be a single float, or it can be a dict with
            keys as service-type and values as floats expressing the calls
            per second for that service. Defaults to None, which means no
            rate-limiting is performed.
        :param oslo_conf: An oslo.config CONF object.
        :type oslo_conf: :class:`~oslo_config.cfg.ConfigOpts`
            An oslo.config ``CONF`` object that has been populated with
            ``keystoneauth1.loading.register_adapter_conf_options`` in
            groups named by the OpenStack service's project name.
        :param service_types:
            A list/set of service types this Connection should support. All
            other service types will be disabled (will error if used).
            **Currently only supported in conjunction with the ``oslo_conf``
            kwarg.**
        :param global_request_id: A Request-id to send with all interactions.
        :param strict_proxies:
            If True, check proxies on creation and raise
            ServiceDiscoveryException if the service is unavailable.
        :type strict_proxies: bool
            Throw an ``openstack.exceptions.ServiceDiscoveryException`` if the
            endpoint for a given service doesn't work. This is useful for
            OpenStack services using sdk to talk to other OpenStack services
            where it can be expected that the deployer config is correct and
            errors should be reported immediately.
            Default false.
        :param kwargs: If a config is not provided, the rest of the parameters
            provided are assumed to be arguments to be passed to the
            CloudRegion constructor.
        """
        self.config = config
        self._extra_services = {}
        self._strict_proxies = strict_proxies
        if extra_services:
            for service in extra_services:
                self._extra_services[service.service_type] = service

        if not self.config:
            if oslo_conf:
                self.config = cloud_region.from_conf(
                    oslo_conf,
                    session=session,
                    app_name=app_name,
                    app_version=app_version,
                    service_types=service_types)
            elif session:
                self.config = cloud_region.from_session(
                    session=session,
                    app_name=app_name,
                    app_version=app_version,
                    load_yaml_config=False,
                    load_envvars=False,
                    rate_limit=rate_limit,
                    **kwargs)
            else:
                self.config = _config.get_cloud_region(cloud=cloud,
                                                       app_name=app_name,
                                                       app_version=app_version,
                                                       load_yaml_config=cloud
                                                       is not None,
                                                       load_envvars=cloud
                                                       is not None,
                                                       rate_limit=rate_limit,
                                                       **kwargs)

        self._session = None
        self._proxies = {}
        self.__pool_executor = None
        self._global_request_id = global_request_id
        self.use_direct_get = use_direct_get
        self.strict_mode = strict
        # Call the _*CloudMixin constructors while we work on
        # integrating things better.
        _cloud._OpenStackCloudMixin.__init__(self)
        _baremetal.BaremetalCloudMixin.__init__(self)
        _block_storage.BlockStorageCloudMixin.__init__(self)
        _clustering.ClusteringCloudMixin.__init__(self)
        _coe.CoeCloudMixin.__init__(self)
        _compute.ComputeCloudMixin.__init__(self)
        _dns.DnsCloudMixin.__init__(self)
        _floating_ip.FloatingIPCloudMixin.__init__(self)
        _identity.IdentityCloudMixin.__init__(self)
        _image.ImageCloudMixin.__init__(self)
        _network_common.NetworkCommonCloudMixin.__init__(self)
        _network.NetworkCloudMixin.__init__(self)
        _object_store.ObjectStoreCloudMixin.__init__(self)
        _orchestration.OrchestrationCloudMixin.__init__(self)
        _security_group.SecurityGroupCloudMixin.__init__(self)

        # Allow vendors to provide hooks. They will normally only receive a
        # connection object and a responsible to register additional services
        vendor_hook = kwargs.get('vendor_hook')
        if not vendor_hook and 'vendor_hook' in self.config.config:
            # Get the one from profile
            vendor_hook = self.config.config.get('vendor_hook')
        if vendor_hook:
            try:
                # NOTE(gtema): no class name in the hook, plain module:function
                # Split string hook into module and function
                try:
                    (package_name, function) = vendor_hook.rsplit(':')

                    if package_name and function:
                        import pkg_resources
                        ep = pkg_resources.EntryPoint('vendor_hook',
                                                      package_name,
                                                      attrs=(function, ))
                        hook = ep.resolve()
                        hook(self)
                except ValueError:
                    self.log.warning('Hook should be in the entrypoint '
                                     'module:attribute format')
            except (ImportError, TypeError) as e:
                self.log.warning('Configured hook %s cannot be executed: %s',
                                 vendor_hook, e)
示例#23
0
    def test_entrypoint_handles_type_extensions(self):
        # loosely based on Pandas test from:
        #   https://github.com/pandas-dev/pandas/pull/27488
        import numba

        def init_function():
            # This init function would normally just call a module init via
            # import or similar, for the sake of testing, inline registration
            # of how to handle the global "_DummyClass".
            class DummyType(numba.types.Type):
                def __init__(self):
                    super(DummyType, self).__init__(name='DummyType')

            @numba.extending.typeof_impl.register(_DummyClass)
            def typer_DummyClass(val, c):
                return DummyType()

            @numba.extending.register_model(DummyType)
            class DummyModel(numba.extending.models.StructModel):
                def __init__(self, dmm, fe_type):
                    members = [
                        ('value', numba.types.float64),
                    ]
                    super(DummyModel, self).__init__(dmm, fe_type, members)

            @numba.extending.unbox(DummyType)
            def unbox_dummy(typ, obj, c):
                value_obj = c.pyapi.object_getattr_string(obj, "value")
                dummy_struct_proxy = numba.core.cgutils.create_struct_proxy(
                    typ)
                dummy_struct = dummy_struct_proxy(c.context, c.builder)
                dummy_struct.value = c.pyapi.float_as_double(value_obj)
                c.pyapi.decref(value_obj)
                err_flag = c.pyapi.err_occurred()
                is_error = numba.core.cgutils.is_not_null(c.builder, err_flag)
                return numba.extending.NativeValue(dummy_struct._getvalue(),
                                                   is_error=is_error)

            @numba.extending.box(DummyType)
            def box_dummy(typ, val, c):
                dummy_struct_proxy = numba.core.cgutils.create_struct_proxy(
                    typ)
                dummy_struct = dummy_struct_proxy(c.context, c.builder)
                value_obj = c.pyapi.float_from_double(dummy_struct.value)
                serialized_clazz = c.pyapi.serialize_object(_DummyClass)
                class_obj = c.pyapi.unserialize(serialized_clazz)
                res = c.pyapi.call_function_objargs(class_obj, (value_obj, ))
                c.pyapi.decref(value_obj)
                c.pyapi.decref(class_obj)
                return res

        mod = types.ModuleType("_test_numba_init_sequence")
        mod.init_func = init_function

        try:
            # will remove this module at the end of the test
            sys.modules[mod.__name__] = mod

            # We are registering an entry point using the "numba" package
            # ("distribution" in pkg_resources-speak) itself, though these are
            # normally registered by other packages.
            dist = "numba"
            entrypoints = pkg_resources.get_entry_map(dist)
            my_entrypoint = pkg_resources.EntryPoint(
                "init",  # name of entry point
                mod.__name__,  # module with entry point object
                attrs=['init_func'],  # name of entry point object
                dist=pkg_resources.get_distribution(dist))
            entrypoints.setdefault('numba_extensions',
                                   {})['init'] = my_entrypoint

            @njit
            def foo(x):
                return x

            ival = _DummyClass(10)
            foo(ival)
        finally:
            # remove fake module
            if mod.__name__ in sys.modules:
                del sys.modules[mod.__name__]
示例#24
0
"""Tests for certbot.plugins.disco."""
import unittest

import mock
import pkg_resources
import six
import zope.interface

from certbot import errors
from certbot import interfaces

from certbot.plugins import standalone
from certbot.plugins import webroot

EP_SA = pkg_resources.EntryPoint("sa",
                                 "certbot.plugins.standalone",
                                 attrs=("Authenticator", ),
                                 dist=mock.MagicMock(key="certbot"))
EP_WR = pkg_resources.EntryPoint("wr",
                                 "certbot.plugins.webroot",
                                 attrs=("Authenticator", ),
                                 dist=mock.MagicMock(key="certbot"))


class PluginEntryPointTest(unittest.TestCase):
    """Tests for certbot.plugins.disco.PluginEntryPoint."""
    def setUp(self):
        self.ep1 = pkg_resources.EntryPoint("ep1",
                                            "p1.ep1",
                                            dist=mock.MagicMock(key="p1"))
        self.ep1prim = pkg_resources.EntryPoint("ep1",
                                                "p2.ep2",
示例#25
0
文件: easteregg.py 项目: diopib/reahl
 def add_entry_point(self, group_name, name, the_class):
     entry = pkg_resources.EntryPoint(name,
                                      the_class.__module__,
                                      attrs=(the_class.__name__, ),
                                      dist=self)
     self.entry_points[(group_name, entry.name)] = entry
示例#26
0
 def mock_iter_entry_points(_t, name=None):
     return [pkg_resources.EntryPoint("fake", "fake", ["fake"])]
示例#27
0
 def fake_entries(group):
     yield pkg_resources.EntryPoint('name1', 'pytest', ('raises',))
示例#28
0
    def dispatch(self,
                 component_type,
                 xml_parent,
                 component,
                 template_data={}):
        """This is a method that you can call from your implementation of
        Base.gen_xml or component.  It allows modules to define a type
        of component, and benefit from extensibility via Python
        entry points and Jenkins Job Builder :ref:`Macros <macro>`.

        :arg string component_type: the name of the component
          (e.g., `builder`)
        :arg YAMLParser parser: the global YAML Parser
        :arg Element xml_parent: the parent XML element
        :arg dict template_data: values that should be interpolated into
          the component definition

        See :py:class:`jenkins_jobs.modules.base.Base` for how to register
        components of a module.

        See the Publishers module for a simple example of how to use
        this method.
        """

        if component_type not in self.modules_by_component_type:
            raise JenkinsJobsException("Unknown component type: "
                                       "'{0}'.".format(component_type))

        entry_point = self.modules_by_component_type[component_type]
        component_list_type = self.get_component_list_type(entry_point)

        if isinstance(component, dict):
            # The component is a singleton dictionary of name: dict(args)
            name, component_data = next(iter(component.items()))
            if template_data or isinstance(component_data, Jinja2Loader):
                # Template data contains values that should be interpolated
                # into the component definition.  To handle Jinja2 templates
                # that don't contain any variables, we also deep format those.
                try:
                    component_data = deep_format(
                        component_data,
                        template_data,
                        self.jjb_config.yamlparser["allow_empty_variables"],
                    )
                except Exception:
                    logging.error(
                        "Failure formatting component ('%s') data '%s'",
                        name,
                        component_data,
                    )
                    raise
        else:
            # The component is a simple string name, eg "run-tests"
            name = component
            component_data = {}

        # Look for a component function defined in an entry point
        eps = self._entry_points_cache.get(component_list_type)
        if eps is None:
            logging.debug("Caching entrypoints for %s" % component_list_type)
            module_eps = []
            # auto build entry points by inferring from base component_types
            mod = pkg_resources.EntryPoint("__all__",
                                           entry_point.module_name,
                                           dist=entry_point.dist)

            Mod = mod.load()
            func_eps = [
                Mod.__dict__.get(a) for a in dir(Mod)
                if isinstance(Mod.__dict__.get(a), types.FunctionType)
            ]
            for func_ep in func_eps:
                try:
                    # extract entry point based on docstring
                    name_line = func_ep.__doc__.split("\n")
                    if not name_line[0].startswith("yaml:"):
                        logger.debug("Ignoring '%s' as an entry point" %
                                     name_line)
                        continue
                    ep_name = name_line[0].split(" ")[1]
                except (AttributeError, IndexError):
                    # AttributeError by docstring not being defined as
                    # a string to have split called on it.
                    # IndexError raised by name_line not containing anything
                    # after the 'yaml:' string.
                    logger.debug("Not including func '%s' as an entry point" %
                                 func_ep.__name__)
                    continue

                module_eps.append(
                    pkg_resources.EntryPoint(
                        ep_name,
                        entry_point.module_name,
                        dist=entry_point.dist,
                        attrs=(func_ep.__name__, ),
                    ))
                logger.debug(
                    "Adding auto EP '%s=%s:%s'" %
                    (ep_name, entry_point.module_name, func_ep.__name__))

            # load from explicitly defined entry points
            module_eps.extend(
                list(
                    pkg_resources.iter_entry_points(
                        group="jenkins_jobs.{0}".format(component_list_type))))

            eps = {}
            for module_ep in module_eps:
                if module_ep.name in eps:
                    raise JenkinsJobsException(
                        "Duplicate entry point found for component type: "
                        "'{0}', '{0}',"
                        "name: '{1}'".format(component_type, name))

                eps[module_ep.name] = module_ep.load()

            # cache both sets of entry points
            self._entry_points_cache[component_list_type] = eps
            logger.debug("Cached entry point group %s = %s",
                         component_list_type, eps)

        # check for macro first
        component = self.parser_data.get(component_type, {}).get(name)
        if component:
            if name in eps and name not in self.masked_warned:
                self.masked_warned[name] = True
                logger.warning("You have a macro ('%s') defined for '%s' "
                               "component type that is masking an inbuilt "
                               "definition" % (name, component_type))

            for b in component[component_list_type]:
                # Pass component_data in as template data to this function
                # so that if the macro is invoked with arguments,
                # the arguments are interpolated into the real defn.
                self.dispatch(component_type, xml_parent, b, component_data)
        elif name in eps:
            func = eps[name]
            func(self, xml_parent, component_data)
        else:
            raise JenkinsJobsException("Unknown entry point or macro '{0}' "
                                       "for component type: '{1}'.".format(
                                           name, component_type))
示例#29
0
文件: __init__.py 项目: wibrt/orange3
def default_entry_point():
    dist = pkg_resources.get_distribution("Orange")
    ep = pkg_resources.EntryPoint("Orange Canvas", __name__, dist=dist)
    return ep
示例#30
0
文件: conf.py 项目: rjmcguire/khufu
import sys
import os
import shlex

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))

import pygments
import pkg_resources

distrib = pkg_resources.Distribution('.', {}, 'khufulexer', '1.0')
distrib.get_entry_map().update({'pygments.lexers':
  {'khufu': pkg_resources.EntryPoint('khufu', 'khufulexer',
                                     attrs=('KhufuLexer',), dist=distrib)}})
pkg_resources.working_set.add(distrib)

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']