Be a bit more relaxed about values for Perc

We now allow float/int for objects, and strings without a trailing % sign.
This commit is contained in:
Florian Bruhin 2017-06-26 21:47:38 +02:00
parent cbf6e4287f
commit 127db2fe42
2 changed files with 18 additions and 13 deletions

View File

@ -632,21 +632,22 @@ class Float(_Numeric):
class Perc(_Numeric):
"""A percentage, as a string ending with %."""
"""A percentage."""
def to_py(self, value):
self._basic_py_validation(value, str)
self._basic_py_validation(value, (float, int, str))
if not value:
return None
if not value.endswith('%'):
raise configexc.ValidationError(value, "does not end with %")
try:
floatval = float(value[:-1])
except ValueError:
raise configexc.ValidationError(value, "must be a percentage!")
self._validate_bounds(floatval, suffix='%')
return floatval
if isinstance(value, str):
value = value.rstrip('%')
try:
value = float(value)
except ValueError:
raise configexc.ValidationError(
value, "must be a valid number!")
self._validate_bounds(value, suffix='%')
return value
def to_str(self, value):
if value is None:

View File

@ -884,19 +884,20 @@ class TestPerc:
@pytest.mark.parametrize('kwargs, val', [
({}, '1337%'),
({}, '1337'),
({}, '1337.42%'),
({}, '1337.42'),
({'maxval': 2}, '2%'),
])
def test_from_str_valid(self, klass, kwargs, val):
assert klass(**kwargs).from_str(val) == val
@pytest.mark.parametrize('kwargs, val', [
({}, '1337'),
({}, '1337%%'),
({}, 'foobar'),
({}, 'foobar%'),
({'minval': 2}, '1%'),
({'maxval': 2}, '3%'),
({'maxval': 2}, '3'),
({'minval': 2, 'maxval': 3}, '1%'),
({'minval': 2, 'maxval': 3}, '4%'),
])
@ -906,6 +907,9 @@ class TestPerc:
@pytest.mark.parametrize('kwargs, val, expected', [
({}, '1337.42%', 1337.42),
({}, '1337.42', 1337.42),
({}, 23, 23),
({}, 23.42, 23.42),
({'minval': 2}, '2.01%', 2.01),
])
def test_to_py_valid(self, klass, kwargs, val, expected):
@ -913,8 +917,8 @@ class TestPerc:
@pytest.mark.parametrize('kwargs, val', [
({}, 'foobar'),
({}, 23),
({'minval': 2, 'maxval': 3}, '1.99%'),
({'minval': 2, 'maxval': 3}, '1.99'),
])
def test_to_py_invalid(self, klass, kwargs, val):
with pytest.raises(configexc.ValidationError):