def __init__(self): if not is_pyethereum16_available(): version = get_pyethereum_version() if version is None: raise pkg_resources.DistributionNotFound( "The `ethereum` package is not available. The " "`PyEthereum16Backend` requires a 1.6.x version of the " "ethereum package to be installed.") elif version not in Spec('>=1.6.0,<1.7.0'): raise pkg_resources.DistributionNotFound( "The `PyEthereum16Backend` requires a 1.6.x version of the " "`ethereum` package. Found {0}".format(version)) self.reset_to_genesis()
def __init__(self): if not is_pyethereum20_available(): version = get_pyethereum_version() if version is None: raise pkg_resources.DistributionNotFound( "The `ethereum` package is not available. The " "`PyEthereum20Backend` requires a 2.0.x version of the " "ethereum package to be installed.") elif version not in Spec('>=2.0.0,<2.1.0'): raise pkg_resources.DistributionNotFound( "The `PyEthereum20Backend` requires a 2.0.x version of the " "`ethereum` package. Found {0}".format(version)) from ethereum.tools import tester self.tester_module = tester self.evm = tester.Chain()
def test_package_version_fallback(self): self.get_distribution_mock.side_effect = \ pkg_resources.DistributionNotFound() self.git_describe_mock.return_value = '1.0.0' self.assertEqual(version.get_package_version('test'), '1.0.0') self.git_describe_mock.assert_called_once()
def test_missing_package(self, getDistributionMock): requirement = 'package' getDistributionMock.side_effect = pkg_resources.DistributionNotFound() self.assertRaisesRegex(MissingPackageError, "mandatory package 'package' not found", verify_packages, requirement)
def test_should_fail_with_distribution_not_found(self, mock_require): mock_require.side_effect = pkg_resources.DistributionNotFound() with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") version_check() self.assertEqual(str(w[-1].message), "gradio is not setup or installed properly. Unable to get version info.")
def test_devel_version(self, mock_stdout, mock_resources): mock_resources.side_effect = pkg_resources.DistributionNotFound() sys.argv = ['/usr/bin/snapcraft', '--version'] with self.assertRaises(SystemExit): snapcraft.main.main() self.assertEqual(mock_stdout.getvalue(), 'devel\n')
def __init__(self): self.fork_config = {} if not is_pyevm_available(): raise pkg_resources.DistributionNotFound( "The `py-evm` package is not available. The " "`PyEVMBackend` requires py-evm to be installed and importable. " "Please install the `py-evm` library.") self.reset_to_genesis()
def test_package_can_only_be_imported(self, import_mock, getDistributionMock): getDistributionMock.side_effect = pkg_resources.DistributionNotFound() package = unittest.mock.Mock() package.__version__ = np.__version__ import_mock.return_value = package verify_packages('numpy')
def _load_commands_for_current_dir(self): egg_info_dir = find_egg_info_dir(os.getcwd()) if egg_info_dir: package_name = os.path.splitext(os.path.basename(egg_info_dir))[0] try: pkg_resources.require(package_name) except pkg_resources.DistributionNotFound as e: msg = '%sNot Found%s: %s (is it an installed Distribution?)' if str(e) != package_name: raise pkg_resources.DistributionNotFound( msg % (str(e) + ': ', ' for', package_name)) else: raise pkg_resources.DistributionNotFound( msg % ('', '', package_name)) dist = pkg_resources.get_distribution(package_name) for epname, ep in dist.get_entry_map('gearbox.plugins').items(): self.load_commands_for_package(ep.module_name)
def detect_version(): try: dist = pkg_resources.get_distribution('yaql') location = os.path.normcase(dist.location) this_location = os.path.normcase(__file__) if not this_location.startswith(os.path.join(location, 'yaql')): raise pkg_resources.DistributionNotFound() return dist.version except pkg_resources.DistributionNotFound: return 'Undefined (package was not installed with setuptools)'
def test_should_fail_with_distribution_not_found(self, mock_require): mock_require.side_effect = pkg_resources.DistributionNotFound() with self.assertRaises(RuntimeError) as e: version_check() self.assertEqual( str(e.exception), "gradio is not setup or installed properly. Unable to get version info." )
def require_version(requirement: str, hint: Optional[str] = None) -> None: """ Perform a runtime check of the dependency versions, using the exact same syntax used by pip. The installed module version comes from the `site-packages` dir via `pkg_resources`. Args: requirement (:obj:`str`): pip style definition, e.g., "tokenizers==0.9.4", "tqdm>=4.27", "numpy" hint (:obj:`str`, `optional`): what suggestion to print in case of requirements not being met """ # note: while pkg_resources.require_version(requirement) is a much simpler way to do it, it # fails if some of the dependencies of the dependencies are not matching, which is not necessarily # bad, hence the more complicated check - which also should be faster, since it doesn't check # dependencies of dependencies. hint = f"\n{hint}" if hint is not None else "" # non-versioned check if re.match(r"^[\w_\-\d]+$", requirement): pkg, op, want_ver = requirement, None, None else: match = re.findall(r"^([^!=<>\s]+)([\s!=<>]{1,2})(.+)", requirement) if not match: raise ValueError( f"requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but got {requirement}" ) pkg, op, want_ver = match[0] if op not in ops: raise ValueError(f"need one of {list(ops.keys())}, but got {op}") # special case if pkg == "python": got_ver = ".".join([str(x) for x in sys.version_info[:3]]) if not ops[op](version.parse(got_ver), version.parse(want_ver)): raise pkg_resources.VersionConflict( f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}." ) return # check if any version is installed try: got_ver = pkg_resources.get_distribution(pkg).version except pkg_resources.DistributionNotFound: raise pkg_resources.DistributionNotFound(requirement, ["this application", hint]) # check that the right version is installed if version number was provided if want_ver is not None and not ops[op](version.parse(got_ver), version.parse(want_ver)): raise pkg_resources.VersionConflict( f"{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}" )
def _mock_get_distribution_which_raises_error(self, distribution_name): """Mock function for pkg_resources.get_distribution(). Args: distribution_name: str. The name of the distribution to get the Distribution object for. Raises: DistributionNotFound. This is always raised, in order to simulate the case where the distribution does not exist (which is what currently happens in a prod environment). """ raise pkg_resources.DistributionNotFound(distribution_name, 'tests')
def test_harness_override_absent_in_unreleased_sdk(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' ]) with mock.patch( 'apache_beam.runners.dataflow.internal.dependency.pkg_resources' '.get_distribution', mock.Mock(side_effect=pkg_resources.DistributionNotFound())): env = apiclient.Environment([], pipeline_options, '2.2.0') self.assertNotIn(override, env.proto.experiments)
def test_harness_override_absent_in_unreleased_sdk(self): pipeline_options = PipelineOptions( ['--temp_location', 'gs://any-location/temp', '--streaming']) with mock.patch( 'apache_beam.runners.dataflow.internal.dependency.pkg_resources' '.get_distribution', mock.Mock(side_effect=pkg_resources.DistributionNotFound())): env = apiclient.Environment( [], #packages pipeline_options, '2.0.0') #any environment version if env.proto.experiments: for experiment in env.proto.experiments: self.assertNotIn('runner_harness_container_image=', experiment)
def check_api_dependencies(): """ This function tests if the API is properly configured. """ try: with open('requirements.txt', 'r') as f: dependencies = list() for line in f.readlines(): dependencies.append(line.strip()) f.close() except: raise FileNotFoundError("requirements.txt file not found or errored.") for dependency in dependencies: dependency_version = get_dependency_version(dependency) try: pkg_resources.require(dependency) except pkg_resources.DistributionNotFound: raise pkg_resources.DistributionNotFound(f'[{dependency}] not found, please check that it is properly installed.') except pkg_resources.VersionConflict: raise pkg_resources.VersionConflict(f'[{dependency}] version errored, since required version is {dependency_version}')
def __init__(self, genesis_overrides=None): """ Example overrides --------------------------------- coinbase: address_bytes difficulty: int(default: 131072) extra_data: bytes gas_limit: int(default: 3141592) gas_used: int(default: 0) nonce: bytes block_number: int timestamp: int(epoch) """ self.fork_config = dict() if not is_pyevm_available(): raise pkg_resources.DistributionNotFound( "The `py-evm` package is not available. The " "`PyEVMBackend` requires py-evm to be installed and importable. " "Please install the `py-evm` library.") self.reset_to_genesis(overrides=genesis_overrides)
def test__get_isort_version() -> None: def get_version() -> VersionRepresentation: _get_isort_version.cache_clear() return _get_isort_version() distro = "pkg_resources.get_distribution" # pass case with mock.patch(distro, return_value=mock.Mock(version="4.3.21")): assert get_version() == VersionRepresentation(4, 3, 21) with mock.patch(distro, return_value=mock.Mock(version="5.1.2")): assert get_version() == VersionRepresentation(5, 1, 2) # incompatible version with pytest.raises(IncompatibleVersionError) as e: with mock.patch(distro, return_value=mock.Mock(version="3.0.0")): get_version() assert "version 3.0.0 is not supported" in str(e) # isort cannot be imported with pytest.raises(DistributionNotFound) as e: with mock.patch( distro, side_effect=pkg_resources.DistributionNotFound("req", "requires") ): get_version() assert "Expected isort to be installed" in str(e)
def test_get_distribution_version_not_found(self, get_distribution): get_distribution.side_effect = pkg_resources.DistributionNotFound() self.assertEqual(spark.get_distribution_version(), 'unknown')
def throw_error(*args, **kwargs): raise pkg_resources.DistributionNotFound('monkeypatched')
def test_get_version_dev_fallback(): with mock.patch.dict(sys.modules, {"ddtrace._version": None}): expected_error = pkg_resources.DistributionNotFound() with mock.patch("pkg_resources.get_distribution") as mock_get_distribution: mock_get_distribution.side_effect = expected_error assert get_version() == "dev"
def raise_not_found(self, dist): raise pkg_resources.DistributionNotFound()
class get_distribution_version_info_TestCase(scaffold.TestCaseWithScenarios): """ Test cases for ‘get_distribution_version_info’ function. """ default_version_info = { 'release_date': "UNKNOWN", 'version': "UNKNOWN", 'maintainer': "UNKNOWN", } scenarios = [ ('version 0.0', { 'test_version_info': json.dumps({ 'version': "0.0", }), 'expected_version_info': {'version': "0.0"}, }), ('version 1.0', { 'test_version_info': json.dumps({ 'version': "1.0", }), 'expected_version_info': {'version': "1.0"}, }), ('file lorem_ipsum.json', { 'version_info_filename': "lorem_ipsum.json", 'test_version_info': json.dumps({ 'version': "1.0", }), 'expected_version_info': {'version': "1.0"}, }), ('not installed', { 'get_distribution_error': pkg_resources.DistributionNotFound(), 'expected_version_info': default_version_info, }), ('no version_info', { 'expected_version_info': default_version_info, }), ] def setUp(self): """ Set up test fixtures. """ super(get_distribution_version_info_TestCase, self).setUp() if hasattr(self, 'expected_resource_name'): self.test_args = {'filename': self.expected_resource_name} else: self.test_args = {} self.expected_resource_name = version_info_filename self.mock_distribution = mock.MagicMock() func_patcher_get_distribution = mock.patch.object( pkg_resources, 'get_distribution') func_patcher_get_distribution.start() self.addCleanup(func_patcher_get_distribution.stop) pkg_resources.get_distribution.side_effect = functools.partial( fake_func_get_distribution, self) def test_requests_installed_distribution(self): """ The package distribution should be retrieved. """ expected_distribution_name = metadata.distribution_name version_info = metadata.get_distribution_version_info(**self.test_args) pkg_resources.get_distribution.assert_called_with( expected_distribution_name) def test_requests_specified_filename(self): """ The specified metadata resource name should be requested. """ if hasattr(self, 'get_distribution_error'): self.skipTest("No access to distribution") version_info = metadata.get_distribution_version_info(**self.test_args) self.mock_distribution.has_metadata.assert_called_with( self.expected_resource_name) def test_result_matches_expected_items(self): """ The result should match the expected items. """ version_info = metadata.get_distribution_version_info(**self.test_args) self.assertEqual(self.expected_version_info, version_info)
def _require_fail(*args, **kwargs): raise pkg_resources.DistributionNotFound('foo', ['my_extras'])