Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'marshmallow' in functional components in Python. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
except TypeError as te:
raise ValidationError(str(te))
@post_load
def make_user(self, data, **kwargs):
return User(**data)
class UserMetaSchema(Schema):
"""The equivalent of the UserSchema, using the ``fields`` option."""
uppername = Uppercased(attribute="name", dump_only=True)
balance = fields.Decimal()
is_old = fields.Method("get_is_old")
lowername = fields.Function(get_lowername)
species = fields.String(attribute="SPECIES")
homepage = fields.Url()
email = fields.Email()
various_data = fields.Dict()
def get_is_old(self, obj):
if obj is None:
return missing
if isinstance(obj, dict):
age = obj.get("age")
else:
age = obj.age
try:
return age > 80
except TypeError as te:
raise ValidationError(str(te))
def test_deserialize_wrong_nested_type_with_validates_method(self, unmarshal):
class TestSchema(Schema):
value = fields.String()
@validates('value')
def validate_value(self, value):
pass
data = {
'foo': 'not what we need'
}
fields_dict = {
'foo': fields.Nested(TestSchema, required=True)
}
with pytest.raises(ValidationError) as excinfo:
result = unmarshal.deserialize(data, fields_dict)
assert result is None
assert excinfo.value.messages == {'foo': {'_schema': ['Invalid input type.']}}
def test_can_use_full_module_path_to_class():
from .foo_serializer import FooSerializer as FooSerializer1 # noqa
# Using full paths is ok
class Schema1(Schema):
foo = fields.Nested('tests.foo_serializer.FooSerializer')
sch = Schema1()
# Note: The arguments here don't matter. What matters is that no
# error is raised
assert sch.dump({'foo': {'_id': 42}}).data
class Schema2(Schema):
foo = fields.Nested('tests.test_registry.FooSerializer')
sch = Schema2()
assert sch.dump({'foo': {'_id': 42}}).data
(mysql.INTEGER, fields.Integer),
(mysql.DATETIME, fields.DateTime),
),
)
def test_convert_types(self, converter, sa_type, field_type):
prop = make_property(sa_type())
field = converter.property2field(prop)
assert type(field) == field_type
def test_session_is_passed_to_nested_field_in_list_field(
self, parent_model, child_model, child_schema, session
):
class ParentSchema(ModelSchema):
children = fields.List(Nested(child_schema))
class Meta:
model = parent_model
data = {"name": "Jorge", "children": [{"name": "Jose"}]}
ParentSchema().load(data, session=session)
assert res[1]["name"] == "name"
assert res[1]["in"] == "query"
def test_raises_error_if_not_a_schema(self, openapi):
class NotASchema:
pass
expected_error = "{!r} doesn't have either `fields` or `_declared_fields`".format(
NotASchema
)
with pytest.raises(ValueError, match=expected_error):
openapi.schema2jsonschema(NotASchema)
class CategorySchema(Schema):
id = fields.Int()
name = fields.Str(required=True)
breed = fields.Str(dump_only=True)
class PageSchema(Schema):
offset = fields.Int()
limit = fields.Int()
class PetSchema(Schema):
category = fields.Nested(CategorySchema, many=True)
name = fields.Str()
class TestNesting:
def test_schema2jsonschema_with_nested_fields(self, spec_fixture):
def test_nested_schema_does_not_create_object():
class TestObject:
def __init__(self, y, nested=None):
self.x = x
self.nested = nested
@version("0")
class Schema(VersionedSchema):
class Meta:
object_class = TestObject
x = marshmallow.fields.Int()
nested = marshmallow.fields.Nested("self", allow_none=True)
deserialized = Schema().load({"x": "1", "nested": {"x": "2"}}, create_object=False)
assert deserialized == {"x": 1, "nested": {"x": 2}}
def convert_BooleanField(self, field, validate=None, **params):
return ma.fields.Int(**params)
def test_cli_invalid_config(self):
with patch('aws_gate.cli.parse_arguments', return_value=MagicMock(subcommand='bootstrap')), \
patch('aws_gate.cli.load_config_from_files', side_effect=ValidationError(message='error')):
with self.assertRaises(ValueError):
main()
def test_package_config_validate(raw, is_valid):
if not is_valid:
with pytest.raises((ValidationError, ValueError)):
PackageConfig.get_from_dict(raw)
else:
PackageConfig.get_from_dict(raw)