Merge pull request #25674 from alfredodeza/wip-rm37442

ceph-volume normalize comma to dot for string to int conversions 

Reviewed-by: Andrew Schoen <aschoen@redhat.com>
This commit is contained in:
Alfredo Deza 2019-01-03 13:44:06 -05:00 committed by GitHub
commit 8cb6de178e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 5 deletions

View File

@ -15,12 +15,27 @@ class TestAsBytes(object):
class TestStrToInt(object):
def test_passing_a_float_str(self):
result = util.str_to_int("1.99")
def test_passing_a_float_str_comma(self):
result = util.str_to_int("1,99")
assert result == 1
def test_passing_a_float_does_not_round(self):
result = util.str_to_int("1.99", round_down=False)
def test_passing_a_float_does_not_round_comma(self):
result = util.str_to_int("1,99", round_down=False)
assert result == 2
@pytest.mark.parametrize("value", ['2', 2])
def test_passing_an_int(self, value):
result = util.str_to_int(value)
assert result == 2
@pytest.mark.parametrize("value", ['1.99', 1.99])
def test_passing_a_float(self, value):
result = util.str_to_int(value)
assert result == 1
@pytest.mark.parametrize("value", ['1.99', 1.99])
def test_passing_a_float_does_not_round(self, value):
result = util.str_to_int(value, round_down=False)
assert result == 2
def test_text_is_not_an_integer_like(self):
@ -28,6 +43,11 @@ class TestStrToInt(object):
util.str_to_int("1.4GB")
assert str(error.value) == "Unable to convert to integer: '1.4GB'"
def test_input_is_not_string(self):
with pytest.raises(RuntimeError) as error:
util.str_to_int(None)
assert str(error.value) == "Unable to convert to integer: 'None'"
def true_responses(upper_casing=False):
if upper_casing:

View File

@ -30,10 +30,21 @@ def str_to_int(string, round_down=True):
"""
Parses a string number into an integer, optionally converting to a float
and rounding down.
Some LVM values may come with a comma instead of a dot to define decimals.
This function normalizes a comma into a dot
"""
error_msg = "Unable to convert to integer: '%s'" % str(string)
try:
integer = float(string)
integer = float(string.replace(',', '.'))
except AttributeError:
# this might be a integer already, so try to use it, otherwise raise
# the original exception
if isinstance(string, (int, float)):
integer = string
else:
logger.exception(error_msg)
raise RuntimeError(error_msg)
except (TypeError, ValueError):
logger.exception(error_msg)
raise RuntimeError(error_msg)