def test_plugin(): distribution = pkg_resources.Distribution(os.path.dirname(__file__)) entry_point = pkg_resources.EntryPoint.parse( 'test = test_plugin:an_example_plugin', dist=distribution) distribution._ep_map = {'segno.plugin.converter': {'test': entry_point}} pkg_resources.working_set.add(distribution) qr = segno.make('The Beatles') assert 'works' == qr.to_test()
def finalize_options(self): self.set_undefined_options('install_lib',('install_dir','install_dir')) ei_cmd = self.get_finalized_command("egg_info") basename = pkg_resources.Distribution( None, None, ei_cmd.egg_name, ei_cmd.egg_version ).egg_name()+'.egg-info' self.source = ei_cmd.egg_info self.target = os.path.join(self.install_dir, basename) self.outputs = [self.target]
def egg_name(self): return ( pkg_resources.Distribution( project_name=self.project_name, version=self.version, platform=(None if self.platform == "any" else get_platform()), ).egg_name() + ".egg" )
def hook_iter_entry_points(group, name=None): if group in ep_packages and ep_packages[group]: eps = ep_packages[group] for ep in eps: parsedEp = pkg_resources.EntryPoint.parse(ep) parsedEp.dist = pkg_resources.Distribution() yield parsedEp else: return default_iter_entry_points(group, name)
def _create_context_manager(group: str, entrypoint: pkg_resources.EntryPoint, working_set: pkg_resources.WorkingSet, scope: str): name = entrypoint.name # We need a Distribution to register our dynamic entrypoints within. # We have to always instantiate it to find our key, as key can be # different from the project_name dist = pkg_resources.Distribution(location=__file__, project_name=scope) # Prevent creating entrypoints in distributions not created by us, # otherwise we could remove the distributions when cleaning up. if (dist.key in working_set.by_key and working_set.by_key[dist.key].location != __file__): raise ValueError(f'scope {format_scope(scope, dist)} already ' f'exists in working set at location ' f'{working_set.by_key[dist.key].location}') if dist.key not in working_set.by_key: working_set.add(dist) # Reference the actual registered dist if we didn't just register it dist = working_set.by_key[dist.key] # Ensure the group exists in our distribution group_entries = dist.get_entry_map().setdefault(group, {}) # Create an entry for the specified entrypoint if name in group_entries: raise ValueError(f'{name!r} is already registered under {group!r} ' f'in scope {format_scope(scope, dist)}') assert entrypoint.dist is None entrypoint.dist = dist group_entries[name] = entrypoint # Wait for something to happen with the entrypoint... try: yield finally: # Tidy up del group_entries[name] # If we re-use this entrypoint (by re-entering the context) the # dist may well have changed (because it gets deleted from the # working set) so we shouldn't remember it. assert entrypoint.dist is dist entrypoint.dist = None if len(group_entries) == 0: del dist.get_entry_map()[group] if len(dist.get_entry_map()) == 0: del working_set.by_key[dist.key] working_set.entry_keys[__file__].remove(dist.key) if not working_set.entry_keys[__file__]: del working_set.entry_keys[__file__] working_set.entries.remove(__file__)
def get_distribution(): """Get the distribution object for this single module dist.""" try: return pkg_resources.get_distribution(DISTRIBUTION_NAME) except pkg_resources.DistributionNotFound as e: capture_exception(e) return pkg_resources.Distribution(project_name=DISTRIBUTION_NAME, version='0.0.0', location=os.path.dirname(__file__))
def test_finder_no_raises_error(self, mock_get_distribution): """ Test the PackageFinder doesn't raises an error when use_wheel is False, and wheel is supported """ mock_get_distribution.return_value = pkg_resources.Distribution( project_name='setuptools', version='0.9') p = PackageFinder([], [], use_wheel=False) p = PackageFinder([], []) p.use_wheel = False
def add_dummy_language_plugin(): distribution = pkg_resources.Distribution(__file__) entry_point = pkg_resources.EntryPoint.parse( "dummy = rpdk.dummy:DummyLanguagePlugin", dist=distribution ) distribution._ep_map = { # pylint: disable=protected-access "rpdk.v1.languages": {"dummy": entry_point} } pkg_resources.working_set.add(distribution)
def __init__(self, *args, **kwargs): ext_dir = pkg_resources.normalize_path('build_ext') dist = pkg_resources.Distribution( ext_dir, project_name='build_ext', metadata=pkg_resources.PathMetadata(ext_dir, ext_dir) ) pkg_resources.working_set.add(dist) Flake8.__init__(self, *args, **kwargs)
def _registerPluginDist(): distribution = pkg_resources.Distribution(__file__) entry_point = pkg_resources.EntryPoint.parse( "awesome-pages = mkdocs_awesome_pages_plugin.plugin:AwesomePagesPlugin", dist=distribution, ) distribution._ep_map = { "mkdocs.plugins": {"awesome-pages": entry_point} } pkg_resources.working_set.add(distribution)
def test_read_dist_line_list(self): # We will mock up a Distribution object with some fake metadata. mock_provider = MockProvider({ 'list.txt': 'reg1\nreg2', }) mock_dist = pkg_resources.Distribution(metadata=mock_provider, project_name='dummydist', version='0.0.0') results = calmjs_dist.read_dist_line_list(mock_dist, 'list.txt') self.assertEqual(results, ['reg1', 'reg2'])
def finalize_options(self): ei_cmd = self.ei_cmd = self.get_finalized_command("egg_info") self.egg_info = ei_cmd.egg_info basename = pkg_resources.Distribution( None, None, ei_cmd.egg_name, ei_cmd.egg_version, get_python_version(), self.distribution.has_ext_modules() and pkg_utils.get_build_platform).egg_name() print basename
def setUp(self) -> None: dist = pkg_resources.Distribution(__file__) ep_map = dict() ep_dcl_fmt = 'test{0} = tests.test_plugin_cli:plgtest' for inx in range(3): ep = pkg_resources.EntryPoint.parse(ep_dcl_fmt.format(inx), dist=dist) ep_map[ep.name] = ep dist._ep_map = {'pyetl_plugins': ep_map} pkg_resources.working_set.add(dist)
def test_read_dist_line_io_error(self): # We will mock up a Distribution object with some fake metadata. stub_stdouts(self) mock_provider = MockProvider({ 'list.txt': None # the MockProvider emulates IOError }) mock_dist = pkg_resources.Distribution(metadata=mock_provider, project_name='dummydist', version='0.0.0') results = calmjs_dist.read_dist_line_list(mock_dist, 'list.txt') self.assertEqual(results, [])
def setUp(self): dist = pkg_resources.Distribution(__file__) ep_map = dict() ep_dcl_fmt = 'test{0} = tests.test_plugin:plgtest' for inx in range(3): ep = pkg_resources.EntryPoint.parse(ep_dcl_fmt.format(inx), dist=dist) ep_map[ep.name] = ep dist._ep_map = {'plugin_nominal': ep_map} pkg_resources.working_set.add(dist) self.registry = PluginRegistry.instance('plugin_nominal')
def setUp(self) -> None: dist = pkg_resources.Distribution(__file__) ep_map = dict() ep_dcl = 'test = tests.test_plugin:not_a_command' ep1 = pkg_resources.EntryPoint.parse(ep_dcl, dist=dist) ep_map[ep1.name] = ep1 dist._ep_map = {'broken_plugins': ep_map} pkg_resources.working_set.add(dist) self.registry = PluginRegistry.instance('broken_plugins')
def test_package_loadable_installed_twice(): """Test that a package is loadable when installed twice. If a package is installed twice, only the first version will be imported. Test that package_loadable will only compare with the first package. """ v1 = pkg_resources.Distribution(project_name='hello', version='1.0.0') v2 = pkg_resources.Distribution(project_name='hello', version='2.0.0') with patch('pkg_resources.find_distributions', side_effect=[[v1]]): assert not package.package_loadable('hello==2.0.0') with patch('pkg_resources.find_distributions', side_effect=[[v1], [v2]]): assert not package.package_loadable('hello==2.0.0') with patch('pkg_resources.find_distributions', side_effect=[[v2], [v1]]): assert package.package_loadable('hello==2.0.0') with patch('pkg_resources.find_distributions', side_effect=[[v2]]): assert package.package_loadable('hello==2.0.0')
def _build_egg_info(name, extractor, setup_file): temp_tar = tempfile.mkdtemp() extractor.extract(temp_tar) extracted_setup_py = os.path.join(temp_tar, setup_file) LOG.info("Building egg info for %s", extracted_setup_py) try: setup_dir = os.path.dirname(extracted_setup_py) output = _run_with_output( [ sys.executable, "-c", SETUPTOOLS_SHIM % extracted_setup_py, "egg_info", "--egg-base", setup_dir, ], cwd=setup_dir, timeout=EGG_INFO_TIMEOUT, ) try: egg_info_dir = [ egg_info for egg_info in os.listdir(setup_dir) if egg_info.endswith(".egg-info") ][0] metadata = pkg_resources.PathMetadata( setup_dir, os.path.join(setup_dir, egg_info_dir) ) pkg_dist = PkgResourcesDistInfo( pkg_resources.Distribution( setup_dir, project_name=name, metadata=metadata ) ) return pkg_dist except IndexError: LOG.error( "Failed to build .egg-info %s:\n%s", list(os.listdir(setup_dir)), output ) except subprocess.CalledProcessError as ex: LOG.warning( 'Failed to build egg-info for %s:\nThe command "%s" produced:\n%s', name, subprocess.list2cmdline(ex.cmd), ex.output, ) try: return _build_wheel(name, os.path.dirname(extracted_setup_py)) finally: shutil.rmtree(temp_tar)
def mocked_require(name: str): if ( name == "pyteal" and version is not None # don't mock if no version is specified ): return [ pkg_resources.Distribution( version=version, ) ] else: return pkg_resources.require(name)[0]
def setup(self): dep = pkg_resources.EntryPoint.parse( 'dummy = test.test_plugins:DummyEventTarget') d = pkg_resources.Distribution() d._ep_map = {'es_logger.plugins.event_target': {'dummy': dep}} pkg_resources.working_set.add(d, 'dummy') ExtensionManager.ENTRY_POINT_CACHE = {} self.esl = es_logger.EsLogger(1000, ['dummy']) self.urls = { 'get_build_env_vars': 'jenkins_url/job/job_name/1/injectedEnvVars/api/json?depth=1', 'get_build_test_report': 'jenkins_url/job/job_name/1/testReport/api/json?depth=1'}
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']
def dummy_plugin_distribution(dummy_plugin_distribution_name, save_sys_path): """Add a dummy plugin distribution to the current working_set.""" dist = pkg_resources.Distribution( project_name=dummy_plugin_distribution_name, metadata=DummyEntryPointMetadata(f""" [lektor.plugins] dummy-plugin = {__name__}:DummyPlugin """), version="1.23", location=__file__, ) pkg_resources.working_set.add(dist) return dist
def prdist(self): """Return a `pkg_resources.Distribution` for this project.""" prdist = pkg_resources.Distribution( location=self.dir, project_name=self.name, version=self.version, ) text = self.read_entry_points() if text: prdist._ep_map = pkg_resources.EntryPoint.parse_map(text, prdist) self.__dict__['prdist'] = prdist # cache value return prdist
def test_get_dist_package_read_error(self): # Quiet stdout from distutils logs stub_stdouts(self) mock_provider = MockProvider({ self.pkgname: None, # None will emulate IO error. }) mock_dist = pkg_resources.Distribution(metadata=mock_provider, project_name='dummydist', version='0.0.0') results = calmjs_dist.read_dist_egginfo_json(mock_dist) # Should still not fail. self.assertIsNone(results)
def test_harness_override_present_in_dataflow_distributions(self): pipeline_options = PipelineOptions( ['--temp_location', 'gs://any-location/temp', '--streaming']) override = ''.join([ 'runner_harness_container_image=', dependency.DATAFLOW_CONTAINER_IMAGE_REPOSITORY, '/harness:2.2.0' ]) distribution = pkg_resources.Distribution(version='2.2.0') with mock.patch( 'apache_beam.runners.dataflow.internal.dependency.pkg_resources' '.get_distribution', mock.MagicMock(return_value=distribution)): env = apiclient.Environment([], pipeline_options, '2.2.0') self.assertIn(override, env.proto.experiments)
def test_read_dist_egginfo_json(self): package_json = {"dependencies": {"left-pad": "~1.1.1"}} # We will mock up a Distribution object with some fake metadata. mock_provider = MockProvider({ self.pkgname: json.dumps(package_json), }) mock_dist = pkg_resources.Distribution(metadata=mock_provider, project_name='dummydist', version='0.0.0') results = calmjs_dist.read_dist_egginfo_json(mock_dist) self.assertEqual(results, package_json)
def find_distribution(module): name = module.__name__ path = get_module_path(module) sources = path_sources.get(path) if sources is None: sources = path_sources[path] = get_sources(path) dist = sources.get(name.replace('.', '/') + '.py') if dist is None: dist = sources.get(name.replace('.', '/') + '/__init__.py') if dist is None: # This is a plain Python source file, not an egg dist = pkg_resources.Distribution(project_name=name, version='', location=module.__file__) return dist
def setup_requirements_json(self): # what kind of bizzaro world do the following users live in? requirements = {"require": {"setuptools": "25.1.6"}} mock_provider = MockProvider({ 'requirements.json': json.dumps(requirements), }) # seriously lolwat? mock_dist = pkg_resources.Distribution(metadata=mock_provider, project_name='calmpy.pip', version='0.0.0') working_set = pkg_resources.WorkingSet() working_set.add(mock_dist) stub_item_attr_value(self, dist, 'default_working_set', working_set) return working_set
def frontend(): mixer = dummy_mixer.create_proxy() audio = dummy_audio.create_proxy() backend = dummy_backend.create_proxy(audio=audio) dummy_core = core.Core.start(audio=audio, mixer=mixer, backends=[backend]).proxy() distribution = pkg_resources.Distribution(__file__) endpoint = pkg_resources.EntryPoint.parse( "dummy = mopidy_pidi.plugin:DisplayDummy", dist=distribution) distribution._ep_map = {"pidi.plugin.display": {"dummy": endpoint}} pkg_resources.working_set.add(distribution, "dummy") config = {"pidi": {"display": "dummy"}, "core": {"data_dir": "/tmp"}} return frontend_lib.PiDiFrontend(config, dummy_core)
def setup_plugin(self, source=""): # This test tests a new plugin appears in breezy.plugin.plugins(). # check the plugin is not loaded already self.assertPluginUnknown('plugin') # write a plugin that _cannot_ fail to load. import pkg_resources d = pkg_resources.Distribution(__file__) ep = pkg_resources.EntryPoint.parse('plugin = ' + __name__ + ':DummyPlugin', dist=d) d._ep_map = {'breezy.plugin': {'plugin': ep}} pkg_resources.working_set.add(d, 'plugin', replace=True) eps = list(pkg_resources.iter_entry_points('breezy.plugin')) self.assertEqual(['plugin'], [ep.name for ep in eps]) self.load_with_paths(['.']) self.addCleanup(d._ep_map.clear)