Fix array attributes validation
This commit is contained in:
@@ -154,3 +154,20 @@ class TestTypes(unittest.TestCase):
|
||||
assert False, 'ValueError was not raised'
|
||||
except ValueError, e:
|
||||
assert str(e) == "Value 'v3' is invalid (should be one of: v1, v2)"
|
||||
|
||||
def test_attribute_validation(self):
|
||||
class AType(object):
|
||||
alist = [int]
|
||||
aint = int
|
||||
|
||||
types.register_type(AType)
|
||||
|
||||
obj = AType()
|
||||
|
||||
obj.alist = [1, 2, 3]
|
||||
assert obj.alist == [1, 2, 3]
|
||||
obj.aint = 5
|
||||
assert obj.aint == 5
|
||||
|
||||
self.assertRaises(ValueError, setattr, obj, 'alist', 12)
|
||||
self.assertRaises(ValueError, setattr, obj, 'alist', [2, 'a'])
|
||||
|
||||
@@ -87,16 +87,27 @@ def iscomplex(datatype):
|
||||
return hasattr(datatype, '_wsme_attributes')
|
||||
|
||||
|
||||
def isarray(datatype):
|
||||
return isinstance(datatype, list)
|
||||
|
||||
|
||||
def validate_value(datatype, value):
|
||||
print datatype
|
||||
if hasattr(datatype, 'validate'):
|
||||
return datatype.validate(value)
|
||||
else:
|
||||
if value is not None and not isinstance(value, datatype):
|
||||
raise ValueError(
|
||||
"Wrong type. Expected '%s', got '%s'" % (
|
||||
datatype, type(value)
|
||||
))
|
||||
if value is not None:
|
||||
if isarray(datatype):
|
||||
if not isinstance(value, list):
|
||||
raise ValueError("Wrong type. Expected '%s', got '%s'" % (
|
||||
datatype, type(value)
|
||||
))
|
||||
for item in value:
|
||||
validate_value(datatype[0], item)
|
||||
elif not isinstance(value, datatype):
|
||||
raise ValueError(
|
||||
"Wrong type. Expected '%s', got '%s'" % (
|
||||
datatype, type(value)
|
||||
))
|
||||
|
||||
|
||||
class wsproperty(property):
|
||||
|
||||
Reference in New Issue
Block a user