Fix number validator

The `integer_types` is always a tuple. When checking
if an instance is a number it fails because it's doing a comparison against a tuple
instead of real type.

➜ python -c "from six import integer_types;import sys;print(integer_types);print(sys.version)"
(<type 'int'>, <type 'long'>)
2.7.16 (default, Apr  6 2019, 01:42:57)
[GCC 8.3.0]

➜ python3 -c "from six import integer_types;import sys;print(integer_types);print(sys.version)"
(<class 'int'>,)
3.7.3 (default, Apr  3 2019, 05:39:12)
[GCC 8.3.0]

And spec defines a number as both int and float https://swagger.io/docs/specification/data-models/data-types/#numbers so both validators need to support both types.
This commit is contained in:
Janez Troha 2019-05-15 18:26:23 +02:00
parent f274836c4d
commit 3339e1311a
2 changed files with 7 additions and 7 deletions

View file

@ -54,7 +54,7 @@ class Schema(object):
SchemaType.ANY: lambda x: True,
SchemaType.BOOLEAN: TypeValidator(bool),
SchemaType.INTEGER: TypeValidator(integer_types, exclude=bool),
SchemaType.NUMBER: TypeValidator(integer_types, float, exclude=bool),
SchemaType.NUMBER: TypeValidator(integer_types + (float, ), exclude=bool),
SchemaType.STRING: TypeValidator(
text_type, date, datetime, binary_type, UUID),
SchemaType.ARRAY: TypeValidator(list, tuple),
@ -228,16 +228,16 @@ class Schema(object):
"Failed to format value {value} to format {type}: {exception}", value, self.format, exc)
def _unmarshal_integer(self, value, custom_formatters=None, strict=True):
if strict and not isinstance(value, (integer_types, )):
if strict and not isinstance(value, integer_types):
raise InvalidSchemaValue("Value {value} is not of type {type}", value, self.type)
return int(value)
def _unmarshal_number(self, value, custom_formatters=None, strict=True):
if strict and not isinstance(value, (float, )):
if strict and not isinstance(value, (float, ) + integer_types):
raise InvalidSchemaValue("Value {value} is not of type {type}", value, self.type)
return float(value)
return value
def _unmarshal_boolean(self, value, custom_formatters=None, strict=True):
if strict and not isinstance(value, (bool, )):

View file

@ -262,12 +262,12 @@ class TestSchemaUnmarshal(object):
with pytest.raises(InvalidSchemaValue):
schema.unmarshal(value)
def test_number_int_invalid(self):
def test_number_int(self):
schema = Schema('number')
value = 1
result = schema.unmarshal(value)
with pytest.raises(InvalidSchemaValue):
schema.unmarshal(value)
assert result == value
class TestSchemaValidate(object):