Python marshmallow.fields.String() Examples

The following are 30 code examples of marshmallow.fields.String(). 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: custom_fields.py    From FlowKit with Mozilla Public License 2.0 7 votes vote down vote up
def __init__(
        self, required=False, validate=None, allow_none=True, missing=None, **kwargs
    ):
        if validate is not None:
            raise ValueError(
                "The EventTypes field provides its own validation "
                "and thus does not accept a the 'validate' argument."
            )

        super().__init__(
            fields.String(validate=OneOf(["calls", "sms", "mds", "topups"])),
            required=required,
            validate=Length(min=1),
            allow_none=allow_none,
            missing=missing,
            **kwargs,
        ) 
Example #2
Source File: test_dump.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_unknown_typed_field():
    class Colour(fields.Field):
        def _jsonschema_type_mapping(self):
            return {"type": "string"}

        def _serialize(self, value, attr, obj):
            r, g, b = value
            r = hex(r)[2:]
            g = hex(g)[2:]
            b = hex(b)[2:]
            return "#" + r + g + b

    class UserSchema(Schema):
        name = fields.String(required=True)
        favourite_colour = Colour()

    schema = UserSchema()

    dumped = validate_and_dump(schema)

    assert dumped["definitions"]["UserSchema"]["properties"]["favourite_colour"] == {
        "type": "string"
    } 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
Source File: test_validation.py    From marshmallow-jsonschema with MIT License 6 votes vote down vote up
def test_regexp():
    ipv4_regex = (
        r"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}"
        r"([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"
    )

    class TestSchema(Schema):
        ip_address = fields.String(validate=validate.Regexp(ipv4_regex))

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    assert dumped["definitions"]["TestSchema"]["properties"]["ip_address"] == {
        "title": "ip_address",
        "type": "string",
        "pattern": ipv4_regex,
    } 
Example #9
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 #10
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 #11
Source File: decorators_test.py    From flask_accepts with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multidict_list_values_interpreted_correctly(app, client):  # noqa
    class TestSchema(Schema):
        name = fields.List(fields.String(), required=True)

    multidict = MultiDict([
        ("name", "value"),
        ("new_value", "still_here")
    ])
    result = _convert_multidict_values_to_schema(multidict, TestSchema())

    # `name` should be converted to a list.
    assert result["name"] == ["value"]

    # `new_value` should *not* be removed here, even though it"s not in the schema.
    assert result["new_value"] == "still_here"

    # Also makes sure handling a list with >1 values also works.
    multidict = MultiDict([
        ("name", "value"),
        ("name", "value2"),
    ])
    result = _convert_multidict_values_to_schema(multidict, TestSchema())
    assert result["name"] == ["value", "value2"] 
Example #12
Source File: test_args.py    From flask-resty with MIT License 6 votes vote down vote up
def schemas():
    class NameSchema(Schema):
        name = fields.String(required=True)

    class NameListSchema(Schema):
        names = fields.List(fields.String(), data_key="name", required=True)

    class NameDelimitedListSchema(Schema):
        names = DelimitedList(fields.String(), data_key="name", required=True)

    class NameDefaultSchema(Schema):
        name = fields.String(missing="foo")

    return {
        "name": NameSchema(),
        "name_list": NameListSchema(),
        "name_delimited_list": NameDelimitedListSchema(),
        "name_default": NameDefaultSchema(),
    } 
Example #13
Source File: test_related.py    From flask-resty with MIT License 6 votes vote down vote up
def schemas():
    class ParentSchema(Schema):
        id = fields.Integer(as_string=True)
        name = fields.String(required=True)

        children = RelatedItem("ChildSchema", many=True, exclude=("parent",))
        child_ids = fields.List(fields.Integer(as_string=True), load_only=True)

    class ChildSchema(Schema):
        @classmethod
        def get_query_options(cls, load):
            return (load.joinedload("parent"),)

        id = fields.Integer(as_string=True)
        name = fields.String(required=True)

        parent = RelatedItem(
            ParentSchema, exclude=("children",), allow_none=True
        )
        parent_id = fields.Integer(
            as_string=True, allow_none=True, load_only=True
        )

    return {"parent": ParentSchema(), "child": ChildSchema()} 
Example #14
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 #15
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 #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_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 #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_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 #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_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 #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_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 #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_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 #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_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_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 #24
Source File: test_fields.py    From flask-resty with MIT License 5 votes vote down vote up
def delimited_list_schema():
    class DelimitedListSchema(Schema):
        ids = DelimitedList(fields.String, required=True)

    return DelimitedListSchema() 
Example #25
Source File: test_fields.py    From flask-resty with MIT License 5 votes vote down vote up
def delimited_list_as_string_schema():
    class DelimitedListAsStringSchema(Schema):
        ids = DelimitedList(fields.String, as_string=True, required=True)

    return DelimitedListAsStringSchema()


# ----------------------------------------------------------------------------- 
Example #26
Source File: test_scheme_from_target.py    From marshmallow-annotations with MIT License 5 votes vote down vote up
def test_doesnt_overwrite_explicitly_declared_fields(registry_):
    class SomeTypeThingScheme(AnnotationSchema):
        id = fields.String()

        class Meta:
            registry = registry_
            target = SomeTypeThing

    id_field = SomeTypeThingScheme._declared_fields["id"]

    assert isinstance(id_field, fields.String) 
Example #27
Source File: test_basic.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)
        name = Column(String, nullable=False)
        description = Column(String)

    db.create_all()

    yield {"widget": Widget}

    db.drop_all() 
Example #28
Source File: test_scheme_from_target.py    From marshmallow-annotations with MIT License 5 votes vote down vote up
def test_doesnt_overwrite_explicitly_declared_fields_from_parent(registry_):
    class SomeTypeThingScheme(AnnotationSchema):
        id = fields.String()

    class SomeTypeThingSchemeJr(SomeTypeThingScheme):
        class Meta:
            registry = registry_
            target = SomeTypeThing

    id_field = SomeTypeThingSchemeJr._declared_fields["id"]

    assert isinstance(id_field, fields.String) 
Example #29
Source File: test_legacy_schema.py    From swagger-marshmallow-codegen with MIT License 5 votes vote down vote up
def test_load_ng__strict(self):
        class S(self._getTargetClass()):
            name = fields.String(required=True)

        with self.assertRaises(ValidationError):
            S(strict=True).load({}) 
Example #30
Source File: test_composite_id.py    From flask-resty with MIT License 5 votes vote down vote up
def models(db):
    class Widget(db.Model):
        __tablename__ = "widgets"

        id_1 = Column(Integer, primary_key=True)
        id_2 = Column(Integer, primary_key=True)
        name = Column(String, nullable=False)

    db.create_all()

    yield {"widget": Widget}

    db.drop_all()