我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用distutils.version.StrictVersion()。
def test_patch_for_similarities(params, extension): file_out_suff = params.get('data', 'file_out_suff') template_file = file_out_suff + '.templates%s.hdf5' %extension if os.path.exists(template_file): try: myfile = h5py.File(template_file, 'r', libver='latest') version = myfile.get('version')[0].decode('ascii') myfile.close() except Exception: version = None else: raise Exception('No templates found! Check suffix?') if version is not None: if (StrictVersion(version) >= StrictVersion('0.6.0')): return True else: print_and_log(["Version is below 0.6.0"], 'debug', logger) return False
def media(self): # taken from django.contrib.admin.options ModelAdmin extra = '' if settings.DEBUG else '.min' # if VERSION <= (1, 8): if StrictVersion(get_version()) < StrictVersion('1.9'): js = [ 'core.js', 'admin/RelatedObjectLookups.js', 'jquery%s.js' % extra, 'jquery.init.js', ] else: js = [ 'core.js', 'vendor/jquery/jquery%s.js' % extra, 'jquery.init.js', 'admin/RelatedObjectLookups.js', 'actions%s.js' % extra, 'urlify.js', 'prepopulate%s.js' % extra, 'vendor/xregexp/xregexp%s.js' % extra, ] return forms.Media(js=[static('admin/js/%s' % url) for url in js])
def need_update(self): if "HTTP_PROXY" in os.environ or "HTTPS_PROXY" in os.environ: if "HTTP_PROXY" in os.environ: if sys.version_info >= (3, 0): proxy = urllib.parse.urlparse(os.environ["HTTP_PROXY"]) else: proxy = urlparse.urlparse(os.environ["HTTP_PROXY"]) else: if sys.version_info >= (3, 0): proxy = urllib.parse.urlparse(os.environ["HTTPS_PROXY"]) else: proxy = urlparse.urlparse(os.environ["HTTPS_PROXY"]) if sys.version_info >= (3, 0): conn = http.client.HTTPSConnection(proxy.hostname, proxy.port) else: conn = httplib.HTTPSConnection(proxy.hostname, proxy.port) conn.set_tunnel(self.version_host, 443) else: if sys.version_info >= (3, 0): conn = http.client.HTTPSConnection("raw.githubusercontent.com") else: conn = httplib.HTTPSConnection("raw.githubusercontent.com") conn.request("GET", self.version_url) version = conn.getresponse().read() try: if StrictVersion(version) > StrictVersion(PYJFUZZ_VERSION): self.new_version = version return True except: pass return False
def make_partition(session, dev, partition_start, partition_end): # Since XS7.0 which has sfdisk V2.23, we observe sfdisk has a bug # that sfdisk will wrongly calculate cylinders when specify Sector # as unit (-uS). That bug will cause the partition operation failed. # And that's fixed in 2.26. So as a workaround, let's use the option # of '--force' for version <=2.25 and >=2.23. '--force' will ignore # the wrong cylinder value but works as expected. VER_FORCE_MIN = '2.23' VER_FORCE_MAX = '2.25' dev_path = utils.make_dev_path(dev) if partition_end != "-": raise pluginlib.PluginError("Can only create unbounded partitions") sfdisk_ver = _get_sfdisk_version() cmd_list = ['sfdisk', '-uS', dev_path] if sfdisk_ver: if StrictVersion(sfdisk_ver) >= StrictVersion(VER_FORCE_MIN) and \ StrictVersion(sfdisk_ver) <= StrictVersion(VER_FORCE_MAX): cmd_list = ['sfdisk', '--force', '-uS', dev_path] utils.run_command(cmd_list, '%s,;\n' % (partition_start))
def main(top_block_cls=commrx, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.setStyleSheetFromFile('dark.qss') tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=scanner, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.setStyleSheetFromFile('/home/jed/radio/dark.qss') tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def test_create_instance(self): instance = TestEChoiceFieldEStrChoicesModel.objects.create(choice=ETestStrChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestStrChoices) self.assertIs(choice, ETestStrChoices.FIELD1) self.assertEqual(choice.value, 'value1') self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestStrChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestStrChoices.choices()) # Default value self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertEqual(instance._meta.fields[1].get_default(), '') # to_python() self.assertIsNone(instance._meta.fields[1].to_python(None)) self.assertRaisesMessage(exceptions.ValidationError, '["Value \'foo\' is not a valid choice."]', instance._meta.fields[1].to_python, 'foo') # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestStrChoices.FIELD1, 'Label 1'), (ETestStrChoices.FIELD2, 'Label 2')]) instance.delete()
def test_create_instance(self): instance = TestEChoiceFieldEIntChoicesModel.objects.create(choice=ETestIntChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestIntChoices) self.assertIs(choice, ETestIntChoices.FIELD1) self.assertEqual(choice.value, 10) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestIntChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestIntChoices.choices()) # Default value self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertIsNone(instance._meta.fields[1].get_default()) # to_python() self.assertRaisesMessage(exceptions.ValidationError, '["\'foo\' value must be an integer."]', instance._meta.fields[1].to_python, 'foo') # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestIntChoices.FIELD1, 'Label 1'), (ETestIntChoices.FIELD2, 'Label 2')]) instance.delete()
def test_create_instance(self): instance = TestEChoiceFieldEFloatChoicesModel.objects.create(choice=ETestFloatChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestFloatChoices) self.assertIs(choice, ETestFloatChoices.FIELD1) self.assertEqual(choice.value, 1.0) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestFloatChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestFloatChoices.choices()) # Default value self.assertIs(instance._meta.fields[1].default, models.fields.NOT_PROVIDED) self.assertIs(instance._meta.fields[1].get_default(), None) # to_python() self.assertRaisesMessage(exceptions.ValidationError, '["\'foo\' value must be a float."]', instance._meta.fields[1].to_python, 'foo') # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestFloatChoices.FIELD1, 'Label 1'), (ETestFloatChoices.FIELD2, 'Label 2')]) instance.delete()
def test_create_instance(self): instance = TestEChoiceFieldDefaultEBoolChoicesModel.objects.create(choice=ETestBoolChoices.FIELD1) choice = instance.choice self.assertIsInstance(choice, ETestBoolChoices) self.assertIs(choice, ETestBoolChoices.FIELD1) self.assertTrue(choice.value) self.assertEqual(choice.label, 'Label 1') if StrictVersion(django_version()) < StrictVersion('1.9.0'): self.assertEqual(instance._meta.fields[1].__class__.__name__, 'EChoiceField') else: self.assertEqual(instance._meta.fields[1].__class__.__name__, 'ETestBoolChoicesField') self.assertEqual(instance._meta.fields[1].choices, ETestBoolChoices.choices()) # Default value self.assertTrue(instance._meta.fields[1].default) self.assertIs(instance._meta.fields[1].get_default(), ETestBoolChoices.FIELD1) # to_python() self.assertTrue(instance._meta.fields[1].to_python('foo')) # Custom flatchoices self.assertEqual(instance._meta.fields[1].flatchoices, [(ETestBoolChoices.FIELD1, 'Label 1'), (ETestBoolChoices.FIELD2, 'Label 2')]) instance.delete()
def get_widgets(self, prefix): # identify names of the widget objects names = self._get_widget_names(prefix) # Get the objects themselves widgets = [getattr(self.ui, this) for this in names] # the double underscore __ is used instead of dash - in qt designer # because dash is not acceptable within the object name. so we must # replace it. We also strip the prefix and suffix (_value) names = [this.replace(prefix + "_", "") for this in names] names = [this.replace("__", "-") for this in names] names = [this.replace("_value", "") for this in names] options = [] snakemake_version = StrictVersion(snakemake.version.__version__) for name, widget in zip(names, widgets): # This option is valid for snakemake above 3.10 if name == "restart-times" and snakemake_version < StrictVersion("3.10"): print("You should use Snakemake 3.10 or above") continue options.append(SOptions(name, widget)) return options
def main(top_block_cls=vor_radio, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def compare_version(v1, v2): """TODO: Compare hyperledger versions >>> v1 = '1.1' >>> v2 = '1.10' >>> compare_version(v1, v2) 1 >>> compare_version(v2, v1) -1 >>> compare_version(v2, v2) 0 """ s1 = StrictVersion(v1) s2 = StrictVersion(v2) if s1 == s2: return 0 elif s1 > s2: return -1 else: return 1
def test_load_transformers(self): config = {'9.0': ['a', 'b']} extensions = {'9.0': { 'a': mock.Mock(name='a'), 'b': mock.Mock(name='b'), }} mock_extman = self.setup_extension_manager(extensions) res = transformations.Manager.load_transformers('testname', config) self.assertEqual(res, [(version.StrictVersion('9.0'), [ extensions['9.0']['a'], extensions['9.0']['b'], ])]) callback = transformations.reraise_endpoint_load_failure self.assertEqual(mock_extman.mock_calls, [ mock.call( 'nailgun.cluster_upgrade.transformations.testname.9.0', on_load_failure_callback=callback, ), ])
def test_apply(self, mock_load, mock_config): mock_trans = mock.Mock() mock_load.return_value = [ (version.StrictVersion('7.0'), [mock_trans.a, mock_trans.b]), (version.StrictVersion('8.0'), [mock_trans.c, mock_trans.d]), (version.StrictVersion('9.0'), [mock_trans.e, mock_trans.f]), ] man = transformations.Manager() res = man.apply('7.0', '9.0', {}) self.assertEqual(res, mock_trans.f.return_value) self.assertEqual(mock_trans.mock_calls, [ mock.call.c({}), mock.call.d(mock_trans.c.return_value), mock.call.e(mock_trans.d.return_value), mock.call.f(mock_trans.e.return_value), ])
def test_crm_version(self, mock_check_output): # xenial mock_check_output.return_value = "crm 2.2.0\n" ret = pcmk.crm_version() self.assertEqual(StrictVersion('2.2.0'), ret) mock_check_output.assert_called_with(['crm', '--version'], universal_newlines=True) # trusty mock_check_output.mock_reset() mock_check_output.return_value = ("1.2.5 (Build f2f315daf6a5fd7ddea8e5" "64cd289aa04218427d)\n") ret = pcmk.crm_version() self.assertEqual(StrictVersion('1.2.5'), ret) mock_check_output.assert_called_with(['crm', '--version'], universal_newlines=True)
def test_get_property(self, mock_crm_version, mock_check_output): mock_crm_version.return_value = StrictVersion('2.2.0') # xenial mock_check_output.return_value = 'false\n' self.assertEqual('false\n', pcmk.get_property('maintenance-mode')) mock_check_output.assert_called_with(['crm', 'configure', 'show-property', 'maintenance-mode'], universal_newlines=True) mock_crm_version.return_value = StrictVersion('2.4.0') mock_check_output.reset_mock() self.assertEqual('false\n', pcmk.get_property('maintenance-mode')) mock_check_output.assert_called_with(['crm', 'configure', 'get-property', 'maintenance-mode'], universal_newlines=True)
def test_get_property_from_xml(self, mock_crm_version, mock_check_output): mock_crm_version.return_value = StrictVersion('1.2.5') # trusty mock_check_output.return_value = CRM_CONFIGURE_SHOW_XML self.assertRaises(pcmk.PropertyNotFound, pcmk.get_property, 'maintenance-mode') mock_check_output.assert_called_with(['crm', 'configure', 'show', 'xml'], universal_newlines=True) mock_check_output.reset_mock() mock_check_output.return_value = CRM_CONFIGURE_SHOW_XML_MAINT_MODE_TRUE self.assertEqual('true', pcmk.get_property('maintenance-mode')) mock_check_output.assert_called_with(['crm', 'configure', 'show', 'xml'], universal_newlines=True)
def get_property(name): """Retrieve a cluster's property :param name: property name :returns: property value :rtype: str """ # crmsh >= 2.3 renamed show-property to get-property, 2.3.x is # available since zesty if crm_version() >= StrictVersion('2.3.0'): output = subprocess.check_output(['crm', 'configure', 'get-property', name], universal_newlines=True) elif crm_version() < StrictVersion('2.2.0'): # before 2.2.0 there is no method to get a property output = subprocess.check_output(['crm', 'configure', 'show', 'xml'], universal_newlines=True) return get_property_from_xml(name, output) else: output = subprocess.check_output(['crm', 'configure', 'show-property', name], universal_newlines=True) return output
def absent(dest, username, check_mode): """ Ensures user is absent Returns (msg, changed) """ if StrictVersion(passlib.__version__) >= StrictVersion('1.6'): ht = HtpasswdFile(dest, new=False) else: ht = HtpasswdFile(dest) if username not in ht.users(): return ("%s not present" % username, False) else: if not check_mode: ht.delete(username) ht.save() return ("Remove %s" % username, True)
def _check_compatibility(self): from distutils.version import StrictVersion cmd = [self.bins['iptables'], '--version'] rc, stdout, stderr = Iptables.module.run_command(cmd, check_rc=False) if rc == 0: result = re.search(r'^ip6tables\s+v(\d+\.\d+)\.\d+$', stdout) if result: version = result.group(1) # CentOS 5 ip6tables (v1.3.x) doesn't support comments, # which means it cannot be used with this module. if StrictVersion(version) < StrictVersion('1.4'): Iptables.module.fail_json(msg="This module isn't compatible with ip6tables versions older than 1.4.x") else: Iptables.module.fail_json(msg="Could not fetch iptables version! Is iptables installed?") # Read rules from the json state file and return a dict.
def is_version_higher(version1, version2): """Check if a version is higher than another. This takes two software versions in the usual b"x.y" form and split them on the decimal character, converting both parts to ints, e.g. b"3.2" becomes (3, 2). It then does a comparison of the two tuples, and returns C{True} if C{version1} is greater than or equal to C{version2}. @param version1: The first version to compare as C{bytes}. @param version2: The second version to compare as C{bytes}. @return: C{True} if the first version is greater than or equal to the second. """ version1 = version1.decode("ascii") version2 = version2.decode("ascii") return StrictVersion(version1) >= StrictVersion(version2)
def main(top_block_cls=fm_receiver, options=None): if StrictVersion("4.5.0") <= StrictVersion(Qt.qVersion()) < StrictVersion("5.0.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.aboutToQuit.connect(quitting) qapp.exec_()
def _needs_format(pipcmd): """ pip >= 9.0.0 needs a --format=legacy argument to avoid a DEPRECATION warning. This function returns True if the nominated pip executable is >= 9.0.0 """ try: return _needs_format_cache[pipcmd] except KeyError: pass # grab the version number output = run([pipcmd, '--version'], stdout=True)[1].decode('utf-8') m = re.match(r'^pip (\S+) from ', output) needs_format = StrictVersion(m.group(1)) >= '9.0.0' _needs_format_cache[pipcmd] = needs_format return needs_format
def main(top_block_cls=top_block, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=top_block, options=None): if options is None: options, _ = argument_parser().parse_args() from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(puncpat=options.puncpat) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def main(top_block_cls=top_block, options=None): if options is None: options, _ = argument_parser().parse_args() from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls(frame_size=options.frame_size, puncpat=options.puncpat) tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def _is_valid(self, *args, **kwargs): """Checks whether the supplied file can be read by this frontend. """ warn_h5py(args[0]) try: f = h5.File(args[0], "r") except (IOError, OSError, ImportError): return False requirements = ["openPMD", "basePath", "meshesPath", "particlesPath"] attrs = list(f["/"].attrs.keys()) for i in requirements: if i not in attrs: f.close() return False known_versions = [StrictVersion("1.0.0"), StrictVersion("1.0.1")] if StrictVersion(f.attrs["openPMD"].decode()) in known_versions: f.close() return True else: f.close() return False
def main(top_block_cls=secplus_rx, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def _check_google_client_version(): try: import pkg_resources except ImportError: raise ImportError('Could not import pkg_resources (setuptools).') # Version 0.28.0 includes many changes compared to previous versions # https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/bigquery/CHANGELOG.md bigquery_client_minimum_version = '0.28.0' _BIGQUERY_CLIENT_VERSION = pkg_resources.get_distribution( 'google-cloud-bigquery').version if (StrictVersion(_BIGQUERY_CLIENT_VERSION) < StrictVersion(bigquery_client_minimum_version)): raise ImportError('pandas requires google-cloud-bigquery >= {0} ' 'for Google BigQuery support, ' 'current version {1}' .format(bigquery_client_minimum_version, _BIGQUERY_CLIENT_VERSION))
def export_views(self, state): gltf_views = [] for key, value in self.buffer_views.items(): gltf = { 'byteLength': value['bytelength'], 'byteOffset': value['byteoffset'], 'name': key, } if state['version'] >= Version('2.0') and value['bytestride'] > 0: gltf['byteStride'] = value['bytestride'] gltf['buffer'] = Reference('buffers', self.name, gltf, 'buffer') state['references'].append(gltf['buffer']) if value['target'] is not None: gltf['target'] = value['target'] gltf_views.append(gltf) state['input']['bufferViews'].append(SimpleID(key)) return gltf_views
def update_extensions(self): self.ext_prop_to_exporter_map = {ext.ext_meta['name']: ext for ext in self.ext_exporters} for exporter in self.ext_exporters: exporter.ext_meta['enable'] = False for prop in self.extension_props: exporter = self.ext_prop_to_exporter_map[prop.name] exporter.ext_meta['enable'] = prop.enable self.extension_props.clear() for exporter in self.ext_exporters: prop = self.extension_props.add() prop.name = exporter.ext_meta['name'] prop.enable = exporter.ext_meta['enable'] if exporter.ext_meta['name'] == 'KHR_technique_webgl': prop.enable = Version(self.asset_version) < Version('2.0')
def check_min_versions(): ret = True # pyaudio vers_required = "0.2.7" vers_current = pyaudio.__version__ if StrictVersion(vers_current) < StrictVersion(vers_required): print("Error: minimum pyaudio vers: {}, current vers {}".format(vers_required, vers_current)) ret = False # librosa vers_required = "0.4.3" vers_current = librosa.__version__ if StrictVersion(vers_current) < StrictVersion(vers_required): print("Error: minimum librosa vers: {}, current vers {}".format(vers_required, vers_current)) ret = False # numpy vers_required = "1.9.0" vers_current = np.__version__ if StrictVersion(vers_current) < StrictVersion(vers_required): print("Error: minimum numpy vers: {}, current vers {}".format(vers_required, vers_current)) ret = False return ret
def main(top_block_cls=top_block, options=None): from distutils.version import StrictVersion if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"): style = gr.prefs().get_string('qtgui', 'style', 'raster') Qt.QApplication.setGraphicsSystem(style) qapp = Qt.QApplication(sys.argv) tb = top_block_cls() tb.start() if GUI: tb.show() def quitting(): tb.stop() tb.wait() qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting) qapp.exec_()
def _check_version(self): if self.version_check: output = await run_subprocess([self.binary, '--version']) match = self._version_re.search(output) if not match: raise ValueError( 'Could not determine version of geckodriver. To ' 'disable version checking, set `version_check` to ' '`False`.' ) version_str = match.group(1) version = StrictVersion(version_str) if version < StrictVersion('0.16.1'): raise ValueError( f'Geckodriver version {version_str} is too old. 0.16.1 or ' f'higher is required. To disable version checking, set ' f'`version_check` to `False`.' )
def test_no_logs_on_empty_changelogs(self): class LegacyInterface(RunnerInterfaceTestImpl): pass class NewerInterface(RunnerInterfaceTestImpl): pass LegacyInterface.version = lambda *_: StrictVersion("0.0.1") NewerInterface.version = lambda *_: StrictVersion("0.0.2") NewerInterface.changelog = lambda *_: None self.test_interfaces = [LegacyInterface, NewerInterface] uut = LegacyInterface('', []) uut.logger = MagicMock() uut._log_legacy_warning() uut.logger.info.assert_not_called() uut.logger.warning.assert_not_called()
def __init__(self, detectors_path: str, detector_id: str, java_options: List[str], requested_release: Optional[str] = None): self.id = detector_id self.base_name = detector_id.split("_", 1)[0] self.path = join(detectors_path, self.id) releases_index_path = join(self.path, Detector.RELEASES_FILE) release = self._get_release(releases_index_path, requested_release) release_tag = release.get("tag", "latest") if "cli_version" in release: cli_version = StrictVersion(release["cli_version"]) else: raise ValueError("Missing CLI version for {}".format(detector_id)) self.md5 = release.get("md5", Detector.NO_MD5) self.jar_path = join(self.path, self.base_name + ".jar") self.jar_url = "{}/{}/{}/{}.jar".format(Detector.BASE_URL, release_tag, cli_version, self.base_name) self.runner_interface = RunnerInterface.get(cli_version, self.jar_path, java_options)
def get_available_versions(): client = boto3.client('s3') paginator = client.get_paginator('list_objects') account_id = boto3.client('sts').get_caller_identity().get('Account') region = boto3.session.Session().region_name s3_bucket = f'{account_id}-{region}-pear-artifacts' versions = list() for page in paginator.paginate(Bucket=s3_bucket, Prefix='pear-website/', Delimiter='/'): prefixes = page.get('CommonPrefixes') try: page_versions = [os.path.basename(os.path.dirname(prefix.get('Prefix'))) for prefix in prefixes] except TypeError: # When there are no prefixes. page_versions = list() versions.extend(page_versions) versions.sort(key=StrictVersion) return versions
def infos_from_giturl(url): """ retrieve the tag or branch from the URL parameter of the action :param url: The URL parameter of the action :return: tag or branch """ pattern = re.compile( r'/(?P<owner>[^/]+)/(?P<name>[^/]+)/archive/(?P<tag>[^/]+)\.zip') m = pattern.search(url) if m: d = m.groupdict() if is_branch(d['tag']): d['branch'] = d['tag'] d['version'] = None d['branch_release'] = d['tag'] else: d['branch'] = 'master' d['branch_release'] = False d['version'] = StrictVersion(d['tag']) else: d = dict(owner=None, name=None, tag=None, branch=None, branch_release=None, version=None) return d