Python pkg_resources.EntryPoint() Examples

The following are 30 code examples of pkg_resources.EntryPoint(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pkg_resources , or try the search function .
Example #1
Source File: test_packaging.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
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) 
Example #2
Source File: test_packaging.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: test___main__.py    From exopy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_running_main_error_in_loading(exopy_qtbot, monkeypatch):
    """Test starting the main app but encountering an error while loading
    modifier.

    """
    import exopy.__main__ as em

    def false_iter(arg):

        class FalseEntryPoint(EntryPoint):
            def load(self, *args, **kwargs):
                raise Exception("Can't load entry point")

        return [FalseEntryPoint('dummy', 'dummy')]

    monkeypatch.setattr(em, 'iter_entry_points', false_iter)

    def check_dialog(qtbot, dial):
        assert 'extension' in dial.text

    with pytest.raises(SystemExit):
        with handle_dialog(exopy_qtbot, 'reject', check_dialog):
            main([]) 
Example #4
Source File: test_packaging.py    From keras-lambda with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: test_packaging.py    From keras-lambda with MIT License 6 votes vote down vote up
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) 
Example #6
Source File: test_fitters.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bad_class(self):
        """This returns a class which doesn't inherient from fitter """
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                mock_entry_badclass = mock.create_autospec(EntryPoint)
                mock_entry_badclass.name = "BadClass"
                mock_entry_badclass.load = self.returnbadclass
                populate_entry_points([mock_entry_badclass])
            except AstropyUserWarning as w:
                if 'modeling.Fitter' in w.args[0]:  # any error for this case should have this in it.
                    pass
                else:
                    raise w
            else:
                raise self.exception_not_thrown 
Example #7
Source File: test_fitters.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_bad_func(self):
        """This returns a function which fails the type check"""
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                mock_entry_badfunc = mock.create_autospec(EntryPoint)
                mock_entry_badfunc.name = "BadFunc"
                mock_entry_badfunc.load = self.returnbadfunc
                populate_entry_points([mock_entry_badfunc])
            except AstropyUserWarning as w:
                if "Class" in w.args[0]:  # any error for this case should have this in it.
                    pass
                else:
                    raise w
            else:
                raise self.exception_not_thrown 
Example #8
Source File: test_fitters.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_import_error(self):
        """This raises an import error on load to test that it is handled correctly"""
        with warnings.catch_warnings():
            warnings.filterwarnings('error')
            try:
                mock_entry_importerror = mock.create_autospec(EntryPoint)
                mock_entry_importerror.name = "IErr"
                mock_entry_importerror.load = self.raiseimporterror
                populate_entry_points([mock_entry_importerror])
            except AstropyUserWarning as w:
                if "ImportError" in w.args[0]:  # any error for this case should have this in it.
                    pass
                else:
                    raise w
            else:
                raise self.exception_not_thrown 
Example #9
Source File: model.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _resource_entry_point(self, name):
        return pkg_resources.EntryPoint(
            name=name,
            module_name="guild.model",
            attrs=("GuildfileResource",),
            dist=self,
        ) 
Example #10
Source File: test_opener.py    From pyfilesystem2 with MIT License 5 votes vote down vote up
def test_registry_protocols(self):
        # Check registry.protocols list the names of all available extension
        extensions = [
            pkg_resources.EntryPoint("proto1", "mod1"),
            pkg_resources.EntryPoint("proto2", "mod2"),
        ]
        m = mock.MagicMock(return_value=extensions)
        with mock.patch.object(
            sys.modules["pkg_resources"], "iter_entry_points", new=m
        ):
            self.assertIn("proto1", opener.registry.protocols)
            self.assertIn("proto2", opener.registry.protocols) 
Example #11
Source File: test_sphinxext.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def _make_ext(name, docstring):
    def inner():
        pass

    inner.__doc__ = docstring
    m1 = mock.Mock(spec=pkg_resources.EntryPoint)
    m1.module_name = '%s_module' % name
    s = mock.Mock(return_value='ENTRY_POINT(%s)' % name)
    m1.__str__ = s
    return extension.Extension(name, m1, inner, None) 
Example #12
Source File: manager.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def _load_plugin(self, ep: pkg_resources.EntryPoint):
        try:
            self.logger.debug(" Loading plugin %s" % ep)
            plugin = ep.load(require=True)
            self.logger.debug(" Initializing plugin %s" % ep)
            plugin_context = copy.copy(self.app_context)
            plugin_context.logger = self.logger.getChild(ep.name)
            obj = plugin(plugin_context)
            return Plugin(ep.name, ep, obj)
        except ImportError as ie:
            self.logger.warning("Plugin %r import failed: %s" % (ep, ie))
        except pkg_resources.UnknownExtra as ue:
            self.logger.warning("Plugin %r dependencies resolution failed: %s" % (ep, ue)) 
Example #13
Source File: test_fitters.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_working(self):
        """This should work fine"""
        mock_entry_working = mock.create_autospec(EntryPoint)
        mock_entry_working.name = "Working"
        mock_entry_working.load = self.successfulimport
        populate_entry_points([mock_entry_working]) 
Example #14
Source File: utils.py    From asphalt with Apache License 2.0 5 votes vote down vote up
def resolve(self, obj):
        """
        Resolve a reference to an entry point or a variable in a module.

        If ``obj`` is a ``module:varname`` reference to an object, :func:`resolve_reference` is
        used to resolve it. If it is a string of any other kind, the named entry point is loaded
        from this container's namespace. Otherwise, ``obj`` is returned as is.

        :param obj: an entry point identifier, an object reference or an arbitrary object
        :return: the loaded entry point, resolved object or the unchanged input value
        :raises LookupError: if ``obj`` was a string but the named entry point was not found

        """
        if not isinstance(obj, str):
            return obj
        if ':' in obj:
            return resolve_reference(obj)

        value = self._entrypoints.get(obj)
        if value is None:
            raise LookupError('no such entry point in {}: {}'.format(self.namespace, obj))

        if isinstance(value, EntryPoint):
            value = self._entrypoints[obj] = value.load()

        return value 
Example #15
Source File: utils.py    From asphalt with Apache License 2.0 5 votes vote down vote up
def all(self) -> List[Any]:
        """
        Load all entry points (if not already loaded) in this namespace and return the resulting
        objects as a list.

        """
        values = []
        for name, value in self._entrypoints.items():
            if isinstance(value, EntryPoint):
                value = self._entrypoints[name] = value.load()

            values.append(value)

        return values 
Example #16
Source File: test_utils.py    From asphalt with Apache License 2.0 5 votes vote down vote up
def container(self):
        container = PluginContainer('asphalt.core.test_plugin_container', BaseDummyPlugin)
        entrypoint = EntryPoint('dummy', 'test_utils')
        entrypoint.load = Mock(return_value=DummyPlugin)
        container._entrypoints = {'dummy': entrypoint}
        return container 
Example #17
Source File: __init__.py    From cloud-inquisitor with Apache License 2.0 5 votes vote down vote up
def get_class_from_ep(self, entry_point):
        return EntryPoint(**entry_point).resolve() 
Example #18
Source File: model.py    From guildai with Apache License 2.0 5 votes vote down vote up
def _model_entry_point(self, model):
        return pkg_resources.EntryPoint(
            name=model.name,
            module_name="guild.model",
            attrs=("GuildfileModel",),
            dist=self,
        ) 
Example #19
Source File: test_base_importer.py    From passpie with MIT License 5 votes vote down vote up
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) 
Example #20
Source File: manager.py    From hbmqtt with MIT License 5 votes vote down vote up
def _load_plugin(self, ep: pkg_resources.EntryPoint):
        try:
            self.logger.debug(" Loading plugin %s" % ep)
            plugin = ep.load(require=True)
            self.logger.debug(" Initializing plugin %s" % ep)
            plugin_context = copy.copy(self.app_context)
            plugin_context.logger = self.logger.getChild(ep.name)
            obj = plugin(plugin_context)
            return Plugin(ep.name, ep, obj)
        except ImportError as ie:
            self.logger.warning("Plugin %r import failed: %s" % (ep, ie))
        except pkg_resources.UnknownExtra as ue:
            self.logger.warning("Plugin %r dependencies resolution failed: %s" % (ep, ue)) 
Example #21
Source File: test_plugin.py    From doit with MIT License 5 votes vote down vote up
def test_add_plugins_from_pkg_resources(self, monkeypatch):
        # mock entry points
        import pkg_resources
        def fake_entries(group):
            yield pkg_resources.EntryPoint('name1', 'pytest', ('raises',))
        monkeypatch.setattr(pkg_resources, 'iter_entry_points', fake_entries)

        plugins = PluginDict()
        plugins.add_plugins({}, 'category2')
        name1 = plugins['name1']
        assert isinstance(name1, PluginEntry)
        assert name1.category == 'category2'
        assert name1.name == 'name1'
        assert name1.location == 'pytest:raises' 
Example #22
Source File: test_sphinxext.py    From stevedore with Apache License 2.0 5 votes vote down vote up
def _make_ext(name, docstring):
    def inner():
        pass

    inner.__doc__ = docstring
    m1 = mock.Mock(spec=pkg_resources.EntryPoint)
    m1.module_name = '%s_module' % name
    s = mock.Mock(return_value='ENTRY_POINT(%s)' % name)
    m1.__str__ = s
    return extension.Extension(name, m1, inner, None) 
Example #23
Source File: master_key_parsing.py    From aws-encryption-sdk-cli with Apache License 2.0 5 votes vote down vote up
def _entry_points():
    # type: () -> DefaultDict[str, Dict[str, pkg_resources.EntryPoint]]
    """Discover all entry points for required groups if they have not already been found.

    :returns: Mapping of group to name to entry points
    :rtype: dict
    """
    if not _ENTRY_POINTS:
        _discover_entry_points()
    return _ENTRY_POINTS 
Example #24
Source File: test_knownimagecrawlers.py    From nichtparasoup with MIT License 5 votes vote down vote up
def test_raise(self) -> None:
        # arrange
        entry = EntryPoint('Test', '__.does.not.exist', attrs=('UnknownClass',),
                           dist=_TEST_PLUGIN_DIST)
        # act & assert
        with self.assertRaises(ImportError):
            KnownImageCrawlers._load(entry) 
Example #25
Source File: __init__.py    From nichtparasoup with MIT License 5 votes vote down vote up
def _load(entry: EntryPoint) -> Any:
        try:
            return entry.load()
        except Exception as ex:
            raise ImportError(f'Error on loading entry {entry}') from ex 
Example #26
Source File: __init__.py    From nichtparasoup with MIT License 5 votes vote down vote up
def _append(self, entry: EntryPoint) -> None:
        self._test_duplicate_name(entry.name)
        loaded = self._load(entry)
        self._test(loaded)
        self._test_duplicate_class(loaded)
        # if everything went well .. add
        self._list[entry.name] = loaded 
Example #27
Source File: __init__.py    From nichtparasoup with MIT License 5 votes vote down vote up
def __init__(self, entries: Iterable[EntryPoint]) -> None:  # pragma: no cover
        self._list: Dict[_ImagecrawlerName, _ImagecrawlerClass] = self._builtins().copy()
        _log('debug', 'Builtin imagecrawlers loaded: %r', self._list)
        for entry in entries:
            try:
                self._append(entry)
            except Exception as ex:  # pylint: disable=broad-except
                _log('debug', 'Entry point skipped: %r from %r\n\t%s', entry.name, entry.dist, ex, exc_info=ex)
            else:
                _log('debug', 'Entry point added: %r from %r', entry.name, entry.dist) 
Example #28
Source File: test_noserunner.py    From spyder-unittest with MIT License 5 votes vote down vote up
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'] 
Example #29
Source File: test_discovery.py    From MLBlocks with MIT License 5 votes vote down vote up
def test__load_entry_points_entry_points(iep_mock):
    # setup
    something_else_ep = EntryPoint('something_else', 'mlblocks.__version__')
    primitives_ep = EntryPoint(
        'primitives',
        'tests.test_discovery',
        attrs=['FAKE_PRIMITIVES_PATH'],
        dist=Distribution()
    )
    another_primitives_ep = EntryPoint(
        'primitives',
        'tests.test_discovery',
        attrs=['FAKE_PRIMITIVES_PATHS'],
        dist=Distribution()
    )
    iep_mock.return_value = [
        something_else_ep,
        primitives_ep,
        another_primitives_ep
    ]

    # run
    paths = discovery._load_entry_points('primitives')

    # assert
    expected = [
        'this/is/a/fake',
        'this/is/another/fake',
        'this/is/yet/another/fake',
    ]
    assert paths == expected

    expected_calls = [
        call('mlblocks'),
    ]
    assert iep_mock.call_args_list == expected_calls 
Example #30
Source File: test___main__.py    From exopy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_running_main_error_in_parser_modifying(exopy_qtbot, monkeypatch):
    """Test starting the main app but encountering an issue while adding
    arguments.

    """
    import exopy.__main__ as em

    def false_iter(arg):

        class FalseEntryPoint(EntryPoint):
            def load(self, *args, **kwargs):

                def false_modifier(parser):
                    raise Exception('Failed to add stupid argument to parser')

                return (false_modifier, 1)

        return [FalseEntryPoint('dummy', 'dummy')]

    monkeypatch.setattr(em, 'iter_entry_points', false_iter)

    def check_dialog(qtbot, dial):
        assert 'modifying' in dial.text

    with pytest.raises(SystemExit):
        with handle_dialog(exopy_qtbot, 'reject', check_dialog):
            main([])