json: raise ValueError invalid list or dict

If the expected datatype is ArrayType or DictType
but the json value is something else raise
ValueError instead of 500 erro because we can browse the
dict or the list.

Closes bug: #1428628

Change-Id: Ibd4d95815c0b81ded8304bba4ca83e6df32d86ae
This commit is contained in:
Mehdi Abaakouk 2015-08-03 14:47:58 +02:00
parent 2cb266eadb
commit 03f0c0b4d6
2 changed files with 28 additions and 1 deletions

View File

@ -156,6 +156,8 @@ def fromjson(datatype, value):
def array_fromjson(datatype, value):
if value is None:
return None
if not isinstance(value, list):
raise ValueError("Value not a valid list: %s" % value)
return [fromjson(datatype.item_type, item) for item in value]
@ -163,6 +165,8 @@ def array_fromjson(datatype, value):
def dict_fromjson(datatype, value):
if value is None:
return None
if not isinstance(value, dict):
raise ValueError("Value not a valid dict: %s" % value)
return dict((
(fromjson(datatype.key_type, item[0]),
fromjson(datatype.value_type, item[1]))

View File

@ -11,7 +11,8 @@ except:
from wsme.rest.json import fromjson, tojson, parse
from wsme.utils import parse_isodatetime, parse_isotime, parse_isodate
from wsme.types import isarray, isdict, isusertype, register_type, UserType
from wsme.types import isarray, isdict, isusertype, register_type
from wsme.types import UserType, ArrayType, DictType
from wsme.rest import expose, validate
from wsme.exc import ClientSideError, InvalidInput
@ -325,6 +326,28 @@ class TestRestJson(wsme.tests.protocol.RestOnlyProtocolTestCase):
j = parse('{"a": "2011-01-01"}', {'a': datetime.date}, False)
assert isinstance(j['a'], datetime.date)
def test_invalid_list_fromjson(self):
jlist = "invalid"
try:
parse('{"a": "%s"}' % jlist, {'a': ArrayType(str)}, False)
assert False
except Exception as e:
assert isinstance(e, InvalidInput)
assert e.fieldname == 'a'
assert e.value == jlist
assert e.msg == "Value not a valid list: %s" % jlist
def test_invalid_dict_fromjson(self):
jdict = "invalid"
try:
parse('{"a": "%s"}' % jdict, {'a': DictType(str, str)}, False)
assert False
except Exception as e:
assert isinstance(e, InvalidInput)
assert e.fieldname == 'a'
assert e.value == jdict
assert e.msg == "Value not a valid dict: %s" % jdict
def test_invalid_date_fromjson(self):
jdate = "2015-01-invalid"
try: