Skip to content

Commit

Permalink
Merge pull request #495 from ergo/master
Browse files Browse the repository at this point in the history
Fix #492 - Make cornice compatible with Marshmallow 2.x and 3.x again
  • Loading branch information
leplatrem committed Oct 8, 2018
2 parents e4e1842 + b89cd6e commit 6524d4a
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
12 changes: 12 additions & 0 deletions cornice/validators/_marshmallow.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ def _validator(request, schema=None, deserializer=None, **kwargs):
:func:`cornice.validators.extract_cstruct`
"""
import marshmallow
try:
from marshmallow.utils import EXCLUDE
except ImportError:
EXCLUDE = 'exclude'

if schema is None:
return
Expand All @@ -61,6 +65,7 @@ def _deserialize(self, value, attr, data):
class Meta(object):
strict = True
ordered = True
unknown = EXCLUDE

class RequestSchemaMeta(type):
"""
Expand Down Expand Up @@ -112,6 +117,13 @@ def _message_normalizer(exc, no_field_name="_schema"):
:return:
"""
if isinstance(exc.messages, dict):
if '_schema' in exc.messages:
new_dict = {}
# if not dict expect a list of dicts and normalize it to just dict
if not hasattr(exc.messages['_schema'], 'keys'):
for item in exc.messages['_schema']:
new_dict.update(item)
return {'_schema': new_dict}
return exc.messages
if len(exc.field_names) == 0:
return {no_field_name: exc.messages}
Expand Down
2 changes: 1 addition & 1 deletion tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -618,7 +618,7 @@ def test_validated_querystring_and_schema_from_same_schema(self):
response = app.post_json('/m_newsletter?ref=2', params=content,
status=400)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json['errors'][0]['description'][0]['email'],
self.assertEqual(response.json['errors'][0]['description'],
'Invalid email length')

def test_validated_path_content_from_schema(self):
Expand Down
41 changes: 41 additions & 0 deletions tests/validationapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,10 @@ def item(request):

try:
import marshmallow
try:
from marshmallow.utils import EXCLUDE
except ImportError:
EXCLUDE = 'exclude'
from cornice.validators import (
marshmallow_validator,
marshmallow_body_validator
Expand All @@ -327,9 +331,15 @@ def item(request):


class MSignupSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
username = marshmallow.fields.String()

class MSignupGroupSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
username = marshmallow.fields.String()

def __init__(self, *args, **kwargs):
Expand All @@ -339,6 +349,9 @@ def __init__(self, *args, **kwargs):
import random

class MNeedsContextSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
somefield = marshmallow.fields.Float(missing=lambda: random.random())
csrf_secret = marshmallow.fields.String()

Expand Down Expand Up @@ -368,6 +381,9 @@ def m_validate_bar(node, value):
raise Invalid(node, "The bar is not open.")

class MBodySchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
# foo and bar are required, baz is optional
foo = marshmallow.fields.String()
bar = SchemaNode(String(), validator=m_validate_bar)
Expand All @@ -377,9 +393,15 @@ class MBodySchema(marshmallow.Schema):
integers = marshmallow.fields.List(marshmallow.fields.Integer())

class MQuery(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
yeah = marshmallow.fields.String()

class MRequestSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
body = marshmallow.fields.Nested(MBodySchema)
querystring = marshmallow.fields.Nested(MQuery)

Expand All @@ -398,6 +420,10 @@ def normalize_field(self, data):
return data

class MQSSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE

querystring = marshmallow.fields.Nested(MListQuerystringSequenced)


Expand All @@ -406,12 +432,21 @@ def m_foobaz_get(request):
return {"field": request.validated['querystring']['field']}

class MNewsletterSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
email = marshmallow.fields.String(validate=marshmallow.validate.Email())

class MRefererSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
ref = marshmallow.fields.Integer()

class MNewsletterPayload(marshmallow.Schema):
class Meta:
unknown = EXCLUDE

body = marshmallow.fields.Nested(MNewsletterSchema)
querystring = marshmallow.fields.Nested(MRefererSchema)

Expand All @@ -429,9 +464,15 @@ def m_newsletter(request):
return request.validated

class MItemPathSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
item_id = marshmallow.fields.Integer(missing=None)

class MItemSchema(marshmallow.Schema):
class Meta:
strict = True
unknown = EXCLUDE
path = marshmallow.fields.Nested(MItemPathSchema)


Expand Down

0 comments on commit 6524d4a

Please sign in to comment.