Skip to content

Commit

Permalink
Warn when using nested instance and many together, raise helpful erro…
Browse files Browse the repository at this point in the history
…r on deserialisations.

marshmallow-code#1982
  • Loading branch information
mmulqueen committed May 3, 2022
1 parent a7034c6 commit 2701553
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 10 deletions.
8 changes: 6 additions & 2 deletions src/marshmallow/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,13 @@ class registry.
"""


class StringNotCollectionError(MarshmallowError, TypeError):
class FieldConfigurationError(MarshmallowError):
"""Raised when trying to configure a field with bad options."""


class StringNotCollectionError(FieldConfigurationError, TypeError):
"""Raised when a string is passed when a list of strings is expected."""


class FieldInstanceResolutionError(MarshmallowError, TypeError):
class FieldInstanceResolutionError(FieldConfigurationError, TypeError):
"""Raised when schema to instantiate is neither a Schema class nor an instance."""
13 changes: 12 additions & 1 deletion src/marshmallow/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@
ValidationError,
StringNotCollectionError,
FieldInstanceResolutionError,
FieldConfigurationError,
)
from marshmallow.validate import And, Length
from marshmallow.warnings import RemovedInMarshmallow4Warning
from marshmallow.warnings import RemovedInMarshmallow4Warning, FieldConfigurationWarning

__all__ = [
"Field",
Expand Down Expand Up @@ -551,6 +552,11 @@ def __init__(
"Use `Nested(lambda: MySchema(...))` instead.",
RemovedInMarshmallow4Warning,
)
if isinstance(nested, SchemaABC) and many:
warnings.warn(
'Passing "many" is ignored if using an instance of a schema. Consider fields.List(fields.Nested(...)) instead.',
FieldConfigurationWarning,
)
self.nested = nested
self.only = only
self.exclude = exclude
Expand Down Expand Up @@ -634,9 +640,14 @@ def _serialize(self, nested_obj, attr, obj, **kwargs):
return schema.dump(nested_obj, many=many)

def _test_collection(self, value):
if self.many and not self.schema.many:
raise FieldConfigurationError(
'"many" may not be used in conjunction with an instance in a nested field.'
)
many = self.schema.many or self.many
if many and not utils.is_collection(value):
raise self.make_error("type", input=value, type=value.__class__.__name__)
# Check whether many on the nested field and the schema are in conflict.

def _load(self, value, data, partial=None):
try:
Expand Down
4 changes: 4 additions & 0 deletions src/marshmallow/warnings.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
class RemovedInMarshmallow4Warning(DeprecationWarning):
pass


class FieldConfigurationWarning(Warning):
pass
4 changes: 2 additions & 2 deletions tests/test_deserialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -1354,7 +1354,7 @@ class PetSchema(Schema):
name = fields.Str()

class StoreSchema(Schema):
pets = fields.Nested(PetSchema(), allow_none=False, many=True)
pets = fields.Nested(PetSchema, allow_none=False, many=True)

sch = StoreSchema()
errors = sch.validate({"pets": None})
Expand All @@ -1378,7 +1378,7 @@ class PetSchema(Schema):
name = fields.Str()

class StoreSchema(Schema):
pets = fields.Nested(PetSchema(), required=True, many=True)
pets = fields.Nested(PetSchema, required=True, many=True)

sch = StoreSchema()
errors = sch.validate({})
Expand Down
17 changes: 16 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
RAISE,
missing,
)
from marshmallow.exceptions import StringNotCollectionError
from marshmallow.exceptions import StringNotCollectionError, FieldConfigurationError
from marshmallow.warnings import FieldConfigurationWarning

from tests.base import ALL_FIELDS

Expand Down Expand Up @@ -395,6 +396,20 @@ class MySchema(Schema):
"nested": {"foo": "baz"}
}

def test_load_instanced_nested_schema_with_many(self):
class NestedSchema(Schema):
foo = fields.String()
bar = fields.String()

with pytest.warns(FieldConfigurationWarning):

class MySchema(Schema):
nested = fields.Nested(NestedSchema(), many=True)

schema = MySchema()
with pytest.raises(FieldConfigurationError):
schema.load({"nested": [{"foo": "123", "bar": "456"}]})


class TestListNested:
@pytest.mark.parametrize("param", ("only", "exclude", "dump_only", "load_only"))
Expand Down
37 changes: 33 additions & 4 deletions tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
StringNotCollectionError,
RegistryError,
)
from marshmallow.warnings import FieldConfigurationWarning

from tests.base import (
UserSchema,
Expand Down Expand Up @@ -2165,18 +2166,46 @@ class ParentSchema(Schema):


class TestPluckSchema:
@pytest.mark.parametrize("user_schema", [UserSchema, UserSchema()])
def test_pluck(self, user_schema, blog):
def test_dump_cls_pluck(self, blog):
class FlatBlogSchema(Schema):
user = fields.Pluck(user_schema, "name")
collaborators = fields.Pluck(user_schema, "name", many=True)
user = fields.Pluck(UserSchema, "name")
collaborators = fields.Pluck(UserSchema, "name", many=True)

s = FlatBlogSchema()
data = s.dump(blog)
assert data["user"] == blog.user.name
for i, name in enumerate(data["collaborators"]):
assert name == blog.collaborators[i].name

def test_dump_instanced_pluck(self, blog):
with pytest.warns(FieldConfigurationWarning):

class FlatBlogSchema(Schema):
user = fields.Pluck(UserSchema(), "name")
collaborators = fields.Pluck(UserSchema(), "name", many=True)

s = FlatBlogSchema()
data = s.dump(blog)
assert data["user"] == blog.user.name
for i, name in enumerate(data["collaborators"]):
assert name == blog.collaborators[i].name

def test_load_pluck(self):
in_data = {
"user": "Doris",
"collaborators": ["Mick", "Keith"],
}

class FlatBlogSchema(Schema):
user = fields.Pluck(UserSchema, "name")
collaborators = fields.Pluck(UserSchema, "name", many=True)

s = FlatBlogSchema()
blog = s.load(in_data)
assert in_data["user"] == blog["user"].name
for i, collab in enumerate(blog["collaborators"]):
assert in_data["collaborators"][i] == collab.name

def test_pluck_none(self, blog):
class FlatBlogSchema(Schema):
user = fields.Pluck(UserSchema, "name")
Expand Down

0 comments on commit 2701553

Please sign in to comment.