Python marshmallow.validate.OneOf() Examples

The following are 19 code examples of marshmallow.validate.OneOf(). 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.validate , 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: joined_spatial_aggregate.py    From FlowKit with Mozilla Public License 2.0 6 votes vote down vote up
def validate_method(self, data, **kwargs):
        continuous_metrics = [
            "radius_of_gyration",
            "unique_location_counts",
            "topup_balance",
            "subscriber_degree",
            "topup_amount",
            "event_count",
            "nocturnal_events",
            "pareto_interactions",
            "displacement",
        ]
        categorical_metrics = ["handset"]
        if data["metric"]["query_kind"] in continuous_metrics:
            validate = OneOf(
                ["avg", "max", "min", "median", "mode", "stddev", "variance"]
            )
        elif data["metric"]["query_kind"] in categorical_metrics:
            validate = OneOf(["distr"])
        else:
            raise ValidationError(
                f"{data['metric']['query_kind']} does not have a valid metric type."
            )
        validate(data["method"])
        return data 
Example #3
Source File: convert.py    From lux with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _add_column_kwargs(self, kwargs, column):
        """Add keyword arguments to kwargs (in-place) based on the passed in
        `Column <sqlalchemy.schema.Column>`.
        """
        if column.nullable:
            kwargs['allow_none'] = True
        kwargs['required'] = not column.nullable and not _has_default(column)

        if hasattr(column.type, 'enums'):
            kwargs['validate'].append(validate.OneOf(choices=column.type.enums))

        # Add a length validator if a max length is set on the column
        # Skip UUID columns
        # (see https://github.com/marshmallow-code/marshmallow-sqlalchemy/issues/54)
        if hasattr(column.type, 'length'):
            try:
                python_type = column.type.python_type
            except (AttributeError, NotImplementedError):
                python_type = None
            if not python_type or not issubclass(python_type, uuid.UUID):
                kwargs['validate'].append(validate.Length(max=column.type.length))

        if hasattr(column.type, 'scale'):
            kwargs['places'] = getattr(column.type, 'scale', None) 
Example #4
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 #5
Source File: test_marshmallow_mongoengine.py    From marshmallow-mongoengine with MIT License 5 votes vote down vote up
def test_sets_enum_choices(self, models):
        fields_ = fields_for_model(models.Course)
        validator = contains_validator(fields_['level'], validate.OneOf)
        assert validator
        assert validator.choices == ('Primary', 'Secondary') 
Example #6
Source File: dispatcher.py    From swagger-marshmallow-codegen with MIT License 5 votes vote down vote up
def dispatch_validator(self, c, value):
        from marshmallow.validate import Length, Regexp, OneOf
        from .validate import Range, MultipleOf, Unique, ItemsRange

        if isinstance(value, (Regexp)):
            c.import_("re")  # xxx
            c.from_("marshmallow.validate", value.__class__.__name__)
        elif isinstance(value, (Length, OneOf)):
            c.from_("marshmallow.validate", value.__class__.__name__)
        elif isinstance(value, (Range, MultipleOf, Unique, ItemsRange)):
            c.from_("swagger_marshmallow_codegen.validate", value.__class__.__name__)
        return value 
Example #7
Source File: aggregation_unit.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, required=True, **kwargs):
        validate = OneOf(["admin0", "admin1", "admin2", "admin3", "lon-lat"])
        super().__init__(required=required, validate=validate, **kwargs) 
Example #8
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, required=True, validate=None, **kwargs):
        if validate is not None:
            raise ValueError(
                "The DFSMetric field provides its own validation and"
                "thus does not accept a the 'validate' argument."
            )

        validate = OneOf(["amount", "commission", "fee", "discount"])
        super().__init__(required=required, validate=validate, **kwargs) 
Example #9
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, required=False, allow_none=True, validate=None, **kwargs):
        if validate is not None:
            raise ValueError(
                "The SubscriberSubset field provides its own validation "
                "and thus does not accept a the 'validate' argument."
            )

        super().__init__(
            required=required, allow_none=allow_none, validate=OneOf([None]), **kwargs
        ) 
Example #10
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, required=True, validate=None, **kwargs):
        if validate is not None:
            raise ValueError(
                "The Statistic field provides its own validation "
                "and thus does not accept a the 'validate' argument."
            )

        validate = OneOf(
            ["avg", "max", "min", "median", "mode", "stddev", "variance"]
        )  # see total_network_objects.py
        super().__init__(required=required, validate=validate, **kwargs) 
Example #11
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, required=False, validate=None, **kwargs):
        if validate is not None:
            raise ValueError(
                "The AggregateBy field provides its own validation "
                "and thus does not accept a the 'validate' argument."
            )

        validate = OneOf(
            ["second", "minute", "hour", "day", "month", "year", "century"]
        )  # see total_network_objects.py
        super().__init__(required=required, validate=validate, **kwargs) 
Example #12
Source File: custom_fields.py    From FlowKit with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, required=False, **kwargs):
        validate = OneOf(
            ["second", "minute", "hour", "day", "month", "year"]
        )  # see total_network_objects.py
        super().__init__(required=required, validate=validate, **kwargs) 
Example #13
Source File: params.py    From marshmallow-mongoengine with MIT License 5 votes vote down vote up
def __init__(self, field_me):
        super(ChoiceParam, self).__init__()
        choices = getattr(field_me, 'choices', None)
        if choices:
            self.field_kwargs['validate'].append(validate.OneOf(choices)) 
Example #14
Source File: parameters.py    From flask-restplus-patched with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        if 'many' in kwargs:
            assert kwargs['many'], "PATCH Parameters must be marked as 'many'"
        kwargs['many'] = True
        super(PatchJSONParameters, self).__init__(*args, **kwargs)
        if not self.PATH_CHOICES:
            raise ValueError("%s.PATH_CHOICES has to be set" % self.__class__.__name__)
        # Make a copy of `validators` as otherwise we will modify the behaviour
        # of all `marshmallow.Schema`-based classes
        self.fields['op'].validators = \
            self.fields['op'].validators + [validate.OneOf(self.OPERATION_CHOICES)]
        self.fields['path'].validators = \
            self.fields['path'].validators + [validate.OneOf(self.PATH_CHOICES)] 
Example #15
Source File: test_environs.py    From environs with MIT License 5 votes vote down vote up
def test_can_add_marshmallow_validator(self, set_env, env):
        set_env({"NODE_ENV": "invalid"})
        with pytest.raises(environs.EnvError):
            env("NODE_ENV", validate=validate.OneOf(["development", "production"])) 
Example #16
Source File: parameters.py    From flask-restplus-server-example with MIT License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        if 'many' in kwargs:
            assert kwargs['many'], "PATCH Parameters must be marked as 'many'"
        kwargs['many'] = True
        super(PatchJSONParameters, self).__init__(*args, **kwargs)
        if not self.PATH_CHOICES:
            raise ValueError("%s.PATH_CHOICES has to be set" % self.__class__.__name__)
        # Make a copy of `validators` as otherwise we will modify the behaviour
        # of all `marshmallow.Schema`-based classes
        self.fields['op'].validators = \
            self.fields['op'].validators + [validate.OneOf(self.OPERATION_CHOICES)]
        self.fields['path'].validators = \
            self.fields['path'].validators + [validate.OneOf(self.PATH_CHOICES)] 
Example #17
Source File: common_schema.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, **metadata):
        super().__init__(**metadata)
        self.validators = (
            [validate.OneOf(WeightRule.all_weight_rules())] + list(self.validators)
        ) 
Example #18
Source File: enum_schemas.py    From airflow with Apache License 2.0 5 votes vote down vote up
def __init__(self, **metadata):
        super().__init__(**metadata)
        self.validators = (
            [validate.OneOf(State.dag_states)] + list(self.validators)
        ) 
Example #19
Source File: test_validation.py    From marshmallow-jsonschema with MIT License 5 votes vote down vote up
def test_one_of_empty_enum():
    class TestSchema(Schema):
        foo = fields.String(validate=OneOf([]))

    schema = TestSchema()

    dumped = validate_and_dump(schema)

    foo_property = dumped["definitions"]["TestSchema"]["properties"]["foo"]
    assert foo_property["enum"] == []
    assert foo_property["enumNames"] == []