From 03f0c0b4d60906ce7a112094ada7df459982a4df Mon Sep 17 00:00:00 2001 From: Mehdi Abaakouk Date: Mon, 3 Aug 2015 14:47:58 +0200 Subject: [PATCH] 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 --- wsme/rest/json.py | 4 ++++ wsme/tests/test_restjson.py | 25 ++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/wsme/rest/json.py b/wsme/rest/json.py index abe3d4a..07448c6 100644 --- a/wsme/rest/json.py +++ b/wsme/rest/json.py @@ -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])) diff --git a/wsme/tests/test_restjson.py b/wsme/tests/test_restjson.py index 23731d6..8099ff1 100644 --- a/wsme/tests/test_restjson.py +++ b/wsme/tests/test_restjson.py @@ -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: