Python marshmallow.fields.Integer() Examples

The following are 30 code examples of marshmallow.fields.Integer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module marshmallow.fields , or try the search function .
Example #1
Source File: test_errors.py    From flask-rebar with MIT License 9 votes vote down vote up
def create_app(self):
        app = Flask(__name__)
        Rebar().init_app(app=app)

        class NestedSchema(validation.RequestSchema):
            baz = fields.List(fields.Integer())

        class Schema(validation.RequestSchema):
            foo = fields.Integer(required=True)
            bar = fields.Email()
            nested = fields.Nested(NestedSchema)

        @app.route("/stuffs", methods=["POST"])
        def json_body_handler():
            data = get_json_body_params_or_400(schema=Schema)
            return response(data)

        return app 
Example #2
Source File: test_validation.py    From marshmallow-jsonschema with MIT License 7 votes vote down vote up
def test_range_marshmallow_3():
    class TestSchema(Schema):
        foo = fields.Integer(
            validate=Range(min=1, min_inclusive=False, max=3, max_inclusive=False)
        )
        bar = fields.Integer(validate=Range(min=2, max=4))

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    props = dumped["definitions"]["TestSchema"]["properties"]
    assert props["foo"]["exclusiveMinimum"] == 1
    assert props["foo"]["exclusiveMaximum"] == 3
    assert props["bar"]["minimum"] == 2
    assert props["bar"]["maximum"] == 4 
Example #3
Source File: test_additional_properties.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_additional_properties_from_nested_meta(additional_properties_value):
    class TestNestedSchema(Schema):
        class Meta:
            additional_properties = additional_properties_value

        foo = fields.Integer()

    class TestSchema(Schema):
        nested = fields.Nested(TestNestedSchema())

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    assert (
        dumped["definitions"]["TestNestedSchema"]["additionalProperties"]
        == additional_properties_value
    ) 
Example #4
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_metadata():
    """Metadata should be available in the field definition."""

    class TestSchema(Schema):
        myfield = fields.String(metadata={"foo": "Bar"})
        yourfield = fields.Integer(required=True, baz="waz")

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    props = dumped["definitions"]["TestSchema"]["properties"]
    assert props["myfield"]["foo"] == "Bar"
    assert props["yourfield"]["baz"] == "waz"
    assert "metadata" not in props["myfield"]
    assert "metadata" not in props["yourfield"]

    # repeat process to assert idempotency
    dumped = validate_and_dump(schema)

    props = dumped["definitions"]["TestSchema"]["properties"]
    assert props["myfield"]["foo"] == "Bar"
    assert props["yourfield"]["baz"] == "waz" 
Example #5
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_dumps_iterable_enums():
    mapping = {"a": 0, "b": 1, "c": 2}

    class TestSchema(Schema):
        foo = fields.Integer(
            validate=validate.OneOf(mapping.values(), labels=mapping.keys())
        )

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    assert dumped["definitions"]["TestSchema"]["properties"]["foo"] == {
        "enum": [v for v in mapping.values()],
        "enumNames": [k for k in mapping.keys()],
        "format": "integer",
        "title": "foo",
        "type": "number",
    } 
Example #6
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_metadata_direct_from_field():
    """Should be able to get metadata without accessing metadata kwarg."""

    class TestSchema(Schema):
        id = fields.Integer(required=True)
        metadata_field = fields.String(description="Directly on the field!")

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    assert dumped["definitions"]["TestSchema"]["properties"]["metadata_field"] == {
        "title": "metadata_field",
        "type": "string",
        "description": "Directly on the field!",
    } 
Example #7
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_nested_recursive():
    """A self-referential schema should not cause an infinite recurse."""

    class RecursiveSchema(Schema):
        foo = fields.Integer(required=True)
        children = fields.Nested("RecursiveSchema", many=True)

    schema = RecursiveSchema()

    dumped = validate_and_dump(schema)

    props = dumped["definitions"]["RecursiveSchema"]["properties"]
    assert "RecursiveSchema" in props["children"]["items"]["$ref"] 
Example #8
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_nested_instance():
    """Should also work with nested schema instances"""

    class TestNestedSchema(Schema):
        baz = fields.Integer()

    class TestSchema(Schema):
        foo = fields.String()
        bar = fields.Nested(TestNestedSchema())

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    nested_def = dumped["definitions"]["TestNestedSchema"]
    nested_obj = dumped["definitions"]["TestSchema"]["properties"]["bar"]

    assert "baz" in nested_def["properties"]
    assert nested_obj["$ref"] == "#/definitions/TestNestedSchema" 
Example #9
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_respect_dotted_exclude_for_nested_schema():
    """Should ignore dotted fields in 'exclude' metadata for nested schemas."""

    class InnerRecursiveSchema(Schema):
        id = fields.Integer(required=True)
        baz = fields.String()
        recursive = fields.Nested("InnerRecursiveSchema")

    class MiddleSchema(Schema):
        id = fields.Integer(required=True)
        bar = fields.String()
        inner = fields.Nested("InnerRecursiveSchema")

    class OuterSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("MiddleSchema", exclude=("inner.recursive",))

    schema = OuterSchema()

    dumped = validate_and_dump(schema)

    inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
    assert "recursive" not in inner_props 
Example #10
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_respect_exclude_for_nested_schema():
    """Should ignore fields in 'exclude' metadata for nested schemas."""

    class InnerRecursiveSchema(Schema):
        id = fields.Integer(required=True)
        baz = fields.String()
        recursive = fields.Nested("InnerRecursiveSchema")

    class MiddleSchema(Schema):
        id = fields.Integer(required=True)
        bar = fields.String()
        inner = fields.Nested("InnerRecursiveSchema", exclude=("recursive",))

    class OuterSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("MiddleSchema")

    schema = OuterSchema()

    dumped = validate_and_dump(schema)

    inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
    assert "recursive" not in inner_props 
Example #11
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_respect_only_for_nested_schema():
    """Should ignore fields not in 'only' metadata for nested schemas."""

    class InnerRecursiveSchema(Schema):
        id = fields.Integer(required=True)
        baz = fields.String()
        recursive = fields.Nested("InnerRecursiveSchema")

    class MiddleSchema(Schema):
        id = fields.Integer(required=True)
        bar = fields.String()
        inner = fields.Nested("InnerRecursiveSchema", only=("id", "baz"))

    class OuterSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("MiddleSchema")

    schema = OuterSchema()
    dumped = validate_and_dump(schema)
    inner_props = dumped["definitions"]["InnerRecursiveSchema"]["properties"]
    assert "recursive" not in inner_props 
Example #12
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_list_nested():
    """Test that a list field will work with an inner nested field."""

    class InnerSchema(Schema):
        foo = fields.Integer(required=True)

    class ListSchema(Schema):
        bar = fields.List(fields.Nested(InnerSchema), required=True)

    schema = ListSchema()
    dumped = validate_and_dump(schema)

    nested_json = dumped["definitions"]["ListSchema"]["properties"]["bar"]

    assert nested_json["type"] == "array"
    assert "items" in nested_json

    item_schema = nested_json["items"]
    assert "InnerSchema" in item_schema["$ref"] 
Example #13
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_nested_string_to_cls():
    class TestNamedNestedSchema(Schema):
        foo = fields.Integer(required=True)

    class TestSchema(Schema):
        foo2 = fields.Integer(required=True)
        nested = fields.Nested("TestNamedNestedSchema")

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    nested_def = dumped["definitions"]["TestNamedNestedSchema"]
    nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
    assert nested_dmp["type"] == "object"
    assert nested_def["properties"]["foo"]["format"] == "integer" 
Example #14
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_nested_descriptions():
    class TestNestedSchema(Schema):
        myfield = fields.String(metadata={"description": "Brown Cow"})
        yourfield = fields.Integer(required=True)

    class TestSchema(Schema):
        nested = fields.Nested(
            TestNestedSchema, metadata={"description": "Nested 1", "title": "Title1"}
        )
        yourfield_nested = fields.Integer(required=True)

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    nested_def = dumped["definitions"]["TestNestedSchema"]
    nested_dmp = dumped["definitions"]["TestSchema"]["properties"]["nested"]
    assert nested_def["properties"]["myfield"]["description"] == "Brown Cow"

    assert nested_dmp["$ref"] == "#/definitions/TestNestedSchema"
    assert nested_dmp["description"] == "Nested 1"
    assert nested_dmp["title"] == "Title1" 
Example #15
Source File: metadata_extensions.py    From invenio-app-ils with MIT License 6 votes vote down vote up
def _validate_marshmallow_type(self, field_cfg):
        """Make sure the Marshmallow type is one we support."""
        def validate_basic_marshmallow_type(_type):
            allowed_types = [
                Bool, DateString, Integer, SanitizedUnicode
            ]
            assert any([
                isinstance(_type, allowed_type) for allowed_type
                in allowed_types
            ])

        marshmallow_type = field_cfg["marshmallow"]
        if isinstance(marshmallow_type, List):
            validate_basic_marshmallow_type(marshmallow_type.inner)
        else:
            validate_basic_marshmallow_type(marshmallow_type) 
Example #16
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_responds_respects_envelope(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @responds(schema=TestSchema, api=api, envelope='test-data')
        def get(self):
            from flask import make_response, Response

            obj = {"_id": 42, "name": "Jon Snow"}
            return obj

    with client as cl:
        resp = cl.get("/test")
        assert resp.status_code == 200
        assert resp.json == {'test-data': {'_id': 42, 'name': 'Jon Snow'}} 
Example #17
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_arguments_are_added_to_request_with_Resource_and_schema(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @accepts(
            "Foo",
            dict(name="foo", type=int, help="An important foo"),
            schema=TestSchema,
            api=api,
        )
        def post(self):
            assert request.parsed_obj
            assert request.parsed_obj["_id"] == 42
            assert request.parsed_obj["name"] == "test name"
            return "success"

    with client as cl:
        resp = cl.post("/test?foo=3", json={"_id": 42, "name": "test name"})
        assert resp.status_code == 200 
Example #18
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_accepts_with_postional_args_query_params_schema_and_header_schema(app, client):  # noqa
    class QueryParamsSchema(Schema):
        query_param = fields.List(fields.String(), required=True)

    class HeadersSchema(Schema):
        Header = fields.Integer(required=True)

    @app.route("/test")
    @accepts(
        dict(name="foo", type=int, help="An important foo"),
        query_params_schema=QueryParamsSchema,
        headers_schema=HeadersSchema)
    def test():
        assert request.parsed_args["foo"] == 3
        assert request.parsed_query_params["query_param"] == ["baz", "qux"]
        assert request.parsed_headers["Header"] == 3
        return "success"

    with client as cl:
        resp = cl.get("/test?foo=3&query_param=baz&query_param=qux", headers={"Header": "3"})
        assert resp.status_code == 200 
Example #19
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_responds(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @responds(schema=TestSchema, api=api)
        def get(self):
            obj = {"_id": 42, "name": "Jon Snow"}
            return obj

    with client as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert obj["_id"] == 42
        assert obj["name"] == "Jon Snow" 
Example #20
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_respond_schema_instance_respects_exclude(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @responds(schema=TestSchema(exclude=("_id",)), api=api)
        def get(self):
            obj = {"_id": 42, "name": "Jon Snow"}
            return obj

    with client as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert "_id" not in obj
        assert obj["name"] == "Jon Snow" 
Example #21
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_respond_schema_respects_many(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @responds(schema=TestSchema, many=True, api=api)
        def get(self):
            obj = [{"_id": 42, "name": "Jon Snow"}]
            return obj

    with client as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert obj == [{"_id": 42, "name": "Jon Snow"}] 
Example #22
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_respond_schema_instance_respects_many(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @responds(schema=TestSchema(many=True), api=api)
        def get(self):
            obj = [{"_id": 42, "name": "Jon Snow"}]
            return obj

    with client as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert obj == [{"_id": 42, "name": "Jon Snow"}] 
Example #23
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_responds_regular_route(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    @app.route("/test", methods=["GET"])
    @responds(schema=TestSchema)
    def get():
        obj = {"_id": 42, "name": "Jon Snow"}
        return obj

    with client as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert obj["_id"] == 42
        assert obj["name"] == "Jon Snow" 
Example #24
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_responds_passes_raw_responses_through_untouched(app, client):  # noqa
    class TestSchema(Schema):
        _id = fields.Integer()
        name = fields.String()

    api = Api(app)

    @api.route("/test")
    class TestResource(Resource):
        @responds(schema=TestSchema, api=api)
        def get(self):
            from flask import make_response, Response

            obj = {"_id": 42, "name": "Jon Snow"}
            return Response("A prebuild response that won't be serialised", 201)

    with client as cl:
        resp = cl.get("/test")
        assert resp.status_code == 201 
Example #25
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_responds_with_validate(app, client):  # noqa
    import pytest
    from flask import jsonify
    from werkzeug.exceptions import InternalServerError

    class TestSchema(Schema):
        _id = fields.Integer(required=True)
        name = fields.String(required=True)

    @app.errorhandler(InternalServerError)
    def payload_validation_failure(err):
        return jsonify({"message": "Server attempted to return invalid data"}), 500

    @app.route("/test")
    @responds(schema=TestSchema, validate=True)
    def get():
        obj = {"wrong_field": 42, "name": "Jon Snow"}
        return obj

    with app.test_client() as cl:
        resp = cl.get("/test")
        obj = resp.json
        assert resp.status_code == 500
        assert resp.json == {"message": "Server attempted to return invalid data"} 
Example #26
Source File: test_one_of_schema.py    From marshmallow-oneofschema with MIT License 6 votes vote down vote up
def test_load_removes_type_field(self):
        class Nonlocal:
            data = None

        class MySchema(m.Schema):
            def load(self, data, *args, **kwargs):
                Nonlocal.data = data
                return super().load(data, *args, **kwargs)

        class FooSchema(MySchema):
            foo = f.String(required=True)

        class BarSchema(MySchema):
            bar = f.Integer(required=True)

        class TestSchema(OneOfSchema):
            type_schemas = {"Foo": FooSchema, "Bar": BarSchema}

        TestSchema().load({"type": "Foo", "foo": "hello"})
        assert "type" not in Nonlocal.data

        TestSchema().load({"type": "Bar", "bar": 123})
        assert "type" not in Nonlocal.data 
Example #27
Source File: test_one_of_schema.py    From marshmallow-oneofschema with MIT License 6 votes vote down vote up
def test_load_keeps_type_field(self):
        class Nonlocal:
            data = None
            type = None

        class MySchema(m.Schema):
            def load(self, data, *args, **kwargs):
                Nonlocal.data = data
                return super().load(data, *args, **kwargs)

        class FooSchema(MySchema):
            foo = f.String(required=True)

        class BarSchema(MySchema):
            bar = f.Integer(required=True)

        class TestSchema(OneOfSchema):
            type_field_remove = False
            type_schemas = {"Foo": FooSchema, "Bar": BarSchema}

        TestSchema(unknown="exclude").load({"type": "Foo", "foo": "hello"})
        assert Nonlocal.data["type"] == "Foo"

        TestSchema(unknown="exclude").load({"type": "Bar", "bar": 123})
        assert Nonlocal.data["type"] == "Bar" 
Example #28
Source File: test_related.py    From flask-resty with MIT License 6 votes vote down vote up
def models(db):
    class Parent(db.Model):
        __tablename__ = "parents"

        id = Column(Integer, primary_key=True)
        name = Column(String)

        children = relationship("Child", backref="parent", cascade="all")

    class Child(db.Model):
        __tablename__ = "children"

        id = Column(Integer, primary_key=True)
        name = Column(String)

        parent_id = Column(ForeignKey(Parent.id))

    db.create_all()

    yield {"parent": Parent, "child": Child}

    db.drop_all() 
Example #29
Source File: test_misc.py    From flask-resty with MIT License 5 votes vote down vote up
def models(db):
    class Widget(db.Model):
        __tablename__ = "widgets"

        id = Column(Integer, primary_key=True)

    db.create_all()

    yield {"widget": Widget}

    db.drop_all() 
Example #30
Source File: utils_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_unpack_nested_self_many():
    app = Flask(__name__)
    api = Api(app)

    class IntegerSchema(Schema):
        my_int = ma.Integer()
        children = ma.Nested("self", exclude=["children"], many=True)

    schema = IntegerSchema()

    result = utils.unpack_nested(schema.fields.get("children"), api=api)

    assert type(result) == fr.List