How to use marshmallow - 10 common examples

To help you get started, we’ve selected a few marshmallow examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github marshmallow-code / marshmallow / tests / base.py View on Github external
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))
github marshmallow-code / marshmallow / tests / test_marshalling.py View on Github external
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.']}}
github marshmallow-code / marshmallow / tests / test_registry.py View on Github external
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
github marshmallow-code / marshmallow-sqlalchemy / tests / test_conversion.py View on Github external
            (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
github marshmallow-code / marshmallow-sqlalchemy / tests / test_model_schema.py View on Github external
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)
github marshmallow-code / apispec / tests / test_ext_marshmallow_openapi.py View on Github external
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):
github PrefectHQ / prefect / tests / serialization / test_versioned_schemas.py View on Github external
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}}
github klen / flask-restler / tests / test_peewee.py View on Github external
def convert_BooleanField(self, field, validate=None, **params):
            return ma.fields.Int(**params)
github xen0l / aws-gate / test / unit / test_cli.py View on Github external
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()
github packit-service / packit / tests / unit / test_package_config.py View on Github external
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)