Merge "Validate body when using Pecan"

This commit is contained in:
Jenkins 2013-10-14 14:19:23 +00:00 committed by Gerrit Code Review
commit b011b2c83f
4 changed files with 19 additions and 2 deletions

View File

@ -14,6 +14,12 @@ class Author(Base):
firstname = text firstname = text
books = wsattr(['Book']) books = wsattr(['Book'])
@staticmethod
def validate(author):
if author.firstname == 'Robert':
raise wsme.exc.ClientSideError("I don't like this author!")
return author
class Book(Base): class Book(Base):
id = int id = int

View File

@ -59,6 +59,17 @@ class TestWS(FunctionalTest):
assert '<id>1</id>' in body assert '<id>1</id>' in body
assert '<firstname>aname</firstname>' in body assert '<firstname>aname</firstname>' in body
def test_post_body_parameter_validation(self):
res = self.app.post(
'/authors', '{"firstname": "Robert"}',
headers={"Content-Type": "application/json"},
expect_errors=True
)
self.assertEqual(res.status_int, 400)
a = json.loads(res.body.decode('utf-8'))
self.assertEqual(a['faultcode'], 'Client')
self.assertEqual(a['faultstring'], "I don't like this author!")
def test_post_body_parameter(self): def test_post_body_parameter(self):
res = self.app.post( res = self.app.post(
'/authors', '{"firstname": "test"}', '/authors', '{"firstname": "test"}',

View File

@ -140,7 +140,7 @@ def fromjson(datatype, value):
elif attrdef.mandatory: elif attrdef.mandatory:
raise InvalidInput(attrdef.name, None, raise InvalidInput(attrdef.name, None,
"Mandatory field missing.") "Mandatory field missing.")
return obj return wsme.types.validate_value(datatype, obj)
elif wsme.types.isusertype(datatype): elif wsme.types.isusertype(datatype):
value = datatype.frombasetype( value = datatype.frombasetype(
fromjson(datatype.basetype, value)) fromjson(datatype.basetype, value))

View File

@ -105,7 +105,7 @@ def fromxml(datatype, element):
elif attrdef.mandatory: elif attrdef.mandatory:
raise InvalidInput(attrdef.name, None, raise InvalidInput(attrdef.name, None,
"Mandatory field missing.") "Mandatory field missing.")
return obj return wsme.types.validate_value(datatype, obj)
if datatype is wsme.types.bytes: if datatype is wsme.types.bytes:
return element.text.encode('ascii') return element.text.encode('ascii')
return datatype(element.text) return datatype(element.text)