config: Improve validate error messages and fix handling of non-string choices.
This commit is contained in:
parent
119644c186
commit
7cb68a41ac
@ -4,19 +4,20 @@ from __future__ import unicode_literals
|
||||
def validate_choice(value, choices):
|
||||
"""Choice validation, normally called in config value's validate()."""
|
||||
if choices is not None and value not in choices :
|
||||
raise ValueError('must be one of %s.' % ', '.join(choices))
|
||||
names = ', '.join(repr(c) for c in choices)
|
||||
raise ValueError('%r must be one of %s.' % (value, names))
|
||||
|
||||
|
||||
def validate_minimum(value, minimum):
|
||||
"""Minimum validation, normally called in config value's validate()."""
|
||||
if minimum is not None and value < minimum:
|
||||
raise ValueError('must be larger than %s.' % minimum)
|
||||
raise ValueError('%r must be larger than %r.' % (value, minimum))
|
||||
|
||||
|
||||
def validate_maximum(value, maximum):
|
||||
"""Maximum validation, normally called in config value's validate()."""
|
||||
if maximum is not None and value > maximum:
|
||||
raise ValueError('must be smaller than %s.' % maximum)
|
||||
raise ValueError('%r must be smaller than %r.' % (value, maximum))
|
||||
|
||||
|
||||
class ConfigValue(object):
|
||||
|
||||
@ -11,6 +11,7 @@ class ValidateChoiceTest(unittest.TestCase):
|
||||
|
||||
def test_valid_value_passes(self):
|
||||
config.validate_choice('foo', ['foo', 'bar', 'baz'])
|
||||
config.validate_choice(1, [1, 2, 3])
|
||||
|
||||
def test_empty_choices_fails(self):
|
||||
with self.assertRaises(ValueError):
|
||||
@ -19,6 +20,8 @@ class ValidateChoiceTest(unittest.TestCase):
|
||||
def test_invalid_value_fails(self):
|
||||
with self.assertRaises(ValueError):
|
||||
config.validate_choice('foobar', ['foo', 'bar', 'baz'])
|
||||
with self.assertRaises(ValueError):
|
||||
config.validate_choice(5, [1, 2, 3])
|
||||
|
||||
|
||||
class ValidateMinimumTest(unittest.TestCase):
|
||||
@ -95,7 +98,6 @@ class StringTest(unittest.TestCase):
|
||||
|
||||
def test_deserialize_enforces_choices(self):
|
||||
value = config.String(choices=['foo', 'bar', 'baz'])
|
||||
|
||||
self.assertEqual('foo', value.deserialize('foo'))
|
||||
with self.assertRaises(ValueError):
|
||||
value.deserialize('foobar')
|
||||
|
||||
Loading…
Reference in New Issue
Block a user