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
python类StrictVersion()的实例源码
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
test_transformations.py 文件源码
项目:fuel-nailgun-extension-cluster-upgrade
作者: openstack
项目源码
文件源码
阅读 23
收藏 0
点赞 0
评论 0
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,
),
])
test_transformations.py 文件源码
项目:fuel-nailgun-extension-cluster-upgrade
作者: openstack
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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):
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):
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):
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_()