Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warnings and errors for incompatible use of schema instance and many in fields.Nested #1983

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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,
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd remove the suggestion.

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.'
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd remove this test. This should be coverered by the init warning you added above, right?

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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this comment was meant for the change above?


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