Beispiel #1
0
def validate_object(obj,
                    field_validators=None,
                    non_field_validators=None,
                    schema=None,
                    context=None):
    """
    Takes a mapping and applies a mapping of validator functions to it
    collecting and reraising any validation errors that occur.
    """
    if schema is None:
        schema = {}
    if context is None:
        context = {}
    if field_validators is None:
        field_validators = ValidationDict()
    if non_field_validators is None:
        non_field_validators = ValidationList()

    from flex.validation.schema import (
        construct_schema_validators, )
    schema_validators = construct_schema_validators(schema, context)
    if '$ref' in schema_validators and hasattr(schema_validators['$ref'],
                                               'validators'):
        ref_ = field_validators.pop('$ref')
        for k, v in ref_.validators.items():
            if k not in schema_validators:
                schema_validators.add_validator(k, v)

    if 'discriminator' in schema:
        add_polymorphism_requirements(obj, schema, context, schema_validators)

    schema_validators.update(field_validators)
    schema_validators.validate_object(obj, context=context)
    non_field_validators.validate_object(obj, context=context)
    return obj
Beispiel #2
0
def validate_object(obj, field_validators=None, non_field_validators=None,
                    schema=None, context=None):
    """
    Takes a mapping and applies a mapping of validator functions to it
    collecting and reraising any validation errors that occur.
    """
    if schema is None:
        schema = {}
    if context is None:
        context = {}
    if field_validators is None:
        field_validators = ValidationDict()
    if non_field_validators is None:
        non_field_validators = ValidationList()

    from flex.validation.schema import (
        construct_schema_validators,
    )
    schema_validators = construct_schema_validators(schema, context)

    if '$ref' in schema_validators and hasattr(schema_validators['$ref'], 'validators'):
        ref_ = field_validators.pop('$ref')
        for k, v in ref_.validators.items():
            if k not in schema_validators:
                schema_validators.add_validator(k, v)

    schema_validators.update(field_validators)

    schema_validators.validate_object(obj, context=context)
    non_field_validators.validate_object(obj, context=context)

    return obj
Beispiel #3
0
def generate_response_body_validator(schema, context, inner=False):
    validators = construct_schema_validators(schema, context=context)
    return chain_reduce_partial(
        operator.attrgetter('data'),
        functools.partial(
            validate_object,
            validators=validators,
            inner=True,
        ),
    )
Beispiel #4
0
def construct_parameter_validators(parameter, context):
    """
    Constructs a dictionary of validator functions for the provided parameter
    definition.
    """
    validators = {}
    if 'schema' in parameter:
        validators.update(construct_schema_validators(parameter['schema'], context=context))
    for key in parameter:
        if key in validator_mapping:
            validators[key] = validator_mapping[key](context=context, **parameter)
    return validators
Beispiel #5
0
def add_polymorphism_requirements(obj, schema, context, schema_validators):
    try:
        object_type = obj[schema['discriminator']]
    except KeyError:
        raise ValidationError("No discriminator found on instance [{0}].".format(obj))

    try:
        object_schema = context['definitions'][object_type]
    except KeyError:
        raise ValidationError("No definition for class [{0}]".format(object_type))

    from flex.validation.schema import (
        construct_schema_validators,
    )
    subtype_validators = construct_schema_validators(object_schema, context)
    schema_validators.update(subtype_validators)
    return schema_validators
Beispiel #6
0
def construct_parameter_validators(parameter, context):
    """
    Constructs a dictionary of validator functions for the provided parameter
    definition.
    """
    validators = ValidationDict()
    for key in parameter:
        if key in validator_mapping:
            validators.add_validator(
                key,
                validator_mapping[key](context=context, **parameter),
            )
    if 'schema' in parameter:
        schema_validators = construct_schema_validators(parameter['schema'],
                                                        context=context)
        for key, value in schema_validators.items():
            validators.setdefault(key, value)
    return validators
Beispiel #7
0
def validate_allof_anyof(value, sub_schemas, context, method, **kwargs):
    from flex.validation.schema import (
        construct_schema_validators, )

    messages = []
    success = []
    for schema in sub_schemas:
        schema_validators = construct_schema_validators(schema, context)
        try:
            schema_validators.validate_object(value, context=context)
        except ValidationError as err:
            messages.append(err.messages)
            success.append(False)
        else:
            success.append(True)

    if not method(success):
        raise ValidationError(messages)

    return value
Beispiel #8
0
def construct_parameter_validators(parameter, context):
    """
    Constructs a dictionary of validator functions for the provided parameter
    definition.
    """
    validators = ValidationDict()
    if '$ref' in parameter:
        validators.add_validator(
            '$ref', ParameterReferenceValidator(parameter['$ref'], context),
        )
    for key in parameter:
        if key in validator_mapping:
            validators.add_validator(
                key,
                validator_mapping[key](context=context, **parameter),
            )
    if 'schema' in parameter:
        schema_validators = construct_schema_validators(parameter['schema'], context=context)
        for key, value in schema_validators.items():
            validators.setdefault(key, value)
    return validators
Beispiel #9
0
def validate_allof_anyof(value, sub_schemas, context, method, **kwargs):
    from flex.validation.schema import (
        construct_schema_validators,
    )

    messages = []
    success = []
    for schema in sub_schemas:
        schema_validators = construct_schema_validators(schema, context)
        try:
            schema_validators.validate_object(value, context=context)
        except ValidationError as err:
            messages.append(err.messages)
            success.append(False)
        else:
            success.append(True)

    if not method(success):
        raise ValidationError(messages)

    return value
Beispiel #10
0
from flex.validation.schema import (
    construct_schema_validators,
)
from flex.decorators import (
    pull_keys_from_obj,
    suffix_reserved_words,
    skip_if_any_kwargs_empty,
)


@pull_keys_from_obj('type', 'minProperties')
@suffix_reserved_words
@skip_if_any_kwargs_empty('type_', 'minProperties')
def validate_type_for_min_properties(type_, minProperties, **kwargs):
    types = pluralize(type_)

    if not set(types).intersection((OBJECT,)):
        raise ValidationError(
            MESSAGES['type']['invalid_type_for_min_properties'],
        )


min_properties_schema = {
    'type': INTEGER,
    'minimum': 0,
}
min_properties_validators = construct_schema_validators(min_properties_schema, {})
min_properties_validator = generate_object_validator(
    field_validators=min_properties_validators,
)
Beispiel #11
0
from flex.constants import (
    STRING,
)
from flex.validation.common import (
    generate_object_validator,
)
from flex.validation.schema import (
    construct_schema_validators,
)


title_schema = {
    'type': STRING,
}
title_validators = construct_schema_validators(title_schema, {})

title_validator = generate_object_validator(
    field_validators=title_validators,
)
Beispiel #12
0
)


@pull_keys_from_obj('minItems', 'maxItems')
def validate_max_items_greater_than_or_equal_to_min_items(
        minItems, maxItems, **kwargs):
    if minItems is EMPTY or maxItems is EMPTY:
        return
    if not maxItems >= minItems:
        raise ValidationError(
            MESSAGES['max_items']['must_be_greater_than_min_items'])


@pull_keys_from_obj('type', 'maxItems')
@suffix_reserved_words
@skip_if_any_kwargs_empty('type_', 'maxItems')
def validate_type_for_max_items(type_, maxItems, **kwargs):
    types = pluralize(type_)

    if not set(types).intersection((ARRAY, )):
        raise ValidationError(MESSAGES['type']['invalid_type_for_max_items'], )


max_items_schema = {
    'type': INTEGER,
}
max_items_validators = construct_schema_validators(max_items_schema, {})

max_items_validator = generate_object_validator(
    field_validators=max_items_validators, )
Beispiel #13
0
    construct_schema_validators,
)


single_type_schema = {
    'type': STRING,
    'enum': [
        NULL,
        BOOLEAN,
        INTEGER,
        NUMBER,
        STRING,
        ARRAY,
    ],
}
single_type_validators = construct_schema_validators(single_type_schema, {})

single_type_validator = generate_object_validator(
    field_validators=single_type_validators,
)


@suffix_reserved_words
@skip_if_not_of_type(ARRAY, STRING)
def validate_types(type_, **kwargs):
    types = pluralize(type_)

    with ErrorList() as errors:
        for value in types:
            try:
                single_type_validator(value)
Beispiel #14
0
from flex.exceptions import ValidationError
from flex.error_messages import MESSAGES
from flex.constants import BOOLEAN, ARRAY
from flex.utils import pluralize
from flex.validation.common import generate_object_validator
from flex.validation.schema import construct_schema_validators
from flex.decorators import pull_keys_from_obj, suffix_reserved_words, skip_if_any_kwargs_empty


@pull_keys_from_obj("type", "uniqueItems")
@suffix_reserved_words
@skip_if_any_kwargs_empty("type_", "uniqueItems")
def validate_type_for_unique_items(type_, uniqueItems, **kwargs):
    types = pluralize(type_)

    if not uniqueItems:
        return

    if not set(types).intersection((ARRAY,)):
        raise ValidationError(MESSAGES["type"]["invalid_type_for_unique_items"])


unique_items_schema = {"type": BOOLEAN}
unique_items_validators = construct_schema_validators(unique_items_schema, {})

unique_items_validator = generate_object_validator(field_validators=unique_items_validators)
Beispiel #15
0
from flex.constants import (
    BOOLEAN,
)
from flex.validation.common import (
    generate_object_validator,
)
from flex.validation.schema import (
    construct_schema_validators,
)


required_schema = {
    'type': BOOLEAN,
}
required_validators = construct_schema_validators(required_schema, {})

required_validator = generate_object_validator(
    field_validators=required_validators,
)
Beispiel #16
0
from flex.decorators import (
    pull_keys_from_obj,
    suffix_reserved_words,
    skip_if_any_kwargs_empty,
)


@pull_keys_from_obj('type', 'uniqueItems')
@suffix_reserved_words
@skip_if_any_kwargs_empty('type_', 'uniqueItems')
def validate_type_for_unique_items(type_, uniqueItems, **kwargs):
    types = pluralize(type_)

    if not uniqueItems:
        return

    if not set(types).intersection((ARRAY,)):
        raise ValidationError(
            MESSAGES['type']['invalid_type_for_unique_items'],
        )


unique_items_schema = {
    'type': BOOLEAN,
}
unique_items_validators = construct_schema_validators(unique_items_schema, {})

unique_items_validator = generate_object_validator(
    field_validators=unique_items_validators,
)
Beispiel #17
0
from flex.constants import (
    STRING, )
from flex.validation.common import (
    generate_object_validator, )
from flex.validation.schema import (
    construct_schema_validators, )

format_schema = {
    'type': STRING,
}
format_validators = construct_schema_validators(format_schema, {})

format_validator = generate_object_validator(
    field_validators=format_validators, )
Beispiel #18
0
from flex.constants import (
    ARRAY, )
from flex.validation.common import (
    generate_object_validator, )
from flex.validation.schema import (
    construct_schema_validators, )

enum_schema = {
    'type': ARRAY,
    'minItems': 1,
}
enum_validators = construct_schema_validators(enum_schema, {})

enum_validator = generate_object_validator(field_validators=enum_validators, )
Beispiel #19
0
)


single_type_schema = {
    'type': STRING,
    'enum': [
        NULL,
        BOOLEAN,
        INTEGER,
        NUMBER,
        STRING,
        ARRAY,
        OBJECT,
    ],
}
single_type_validators = construct_schema_validators(single_type_schema, {})

single_type_validator = generate_object_validator(
    field_validators=single_type_validators,
)


@suffix_reserved_words
@skip_if_not_of_type(ARRAY, STRING)
def validate_types(type_, **kwargs):
    types = pluralize(type_)

    with ErrorList() as errors:
        for value in types:
            try:
                single_type_validator(value)
Beispiel #20
0
from flex.constants import (
    STRING,
)
from flex.validation.common import (
    generate_object_validator,
)
from flex.validation.schema import (
    construct_schema_validators,
)


format_schema = {
    'type': STRING,
}
format_validators = construct_schema_validators(format_schema, {})

format_validator = generate_object_validator(
    field_validators=format_validators,
)
Beispiel #21
0
from flex.constants import (
    BOOLEAN,
)
from flex.validation.common import (
    generate_object_validator,
)
from flex.validation.schema import (
    construct_schema_validators,
)


read_only_schema = {
    'type': BOOLEAN,
}
read_only_validators = construct_schema_validators(read_only_schema, {})

read_only_validator = generate_object_validator(
    field_validators=read_only_validators,
)
Beispiel #22
0
)
from flex.validation.schema import (
    construct_schema_validators,
)
from flex.decorators import (
    skip_if_empty,
    skip_if_not_of_type,
)


@skip_if_empty
@skip_if_not_of_type(STRING)
def regex_validator(value, **kwargs):
    try:
        re.compile(value)
    except re.error:
        raise ValidationError(
            MESSAGES['pattern']['invalid_regex'].format(value)
        )


pattern_schema = {
    'type': STRING,
}
pattern_validators = construct_schema_validators(pattern_schema, {})
pattern_validators.add_validator('regex', regex_validator)

pattern_validator = generate_object_validator(
    field_validators=pattern_validators,
)
Beispiel #23
0
from flex.error_messages import MESSAGES
from flex.constants import INTEGER, EMPTY, ARRAY
from flex.utils import pluralize
from flex.validation.common import generate_object_validator
from flex.validation.schema import construct_schema_validators
from flex.decorators import pull_keys_from_obj, suffix_reserved_words, skip_if_any_kwargs_empty


@pull_keys_from_obj("minItems", "maxItems")
def validate_max_items_greater_than_or_equal_to_min_items(minItems, maxItems, **kwargs):
    if minItems is EMPTY or maxItems is EMPTY:
        return
    if not maxItems >= minItems:
        raise ValidationError(MESSAGES["max_items"]["must_be_greater_than_min_items"])


@pull_keys_from_obj("type", "maxItems")
@suffix_reserved_words
@skip_if_any_kwargs_empty("type_", "maxItems")
def validate_type_for_max_items(type_, maxItems, **kwargs):
    types = pluralize(type_)

    if not set(types).intersection((ARRAY,)):
        raise ValidationError(MESSAGES["type"]["invalid_type_for_max_items"])


max_items_schema = {"type": INTEGER}
max_items_validators = construct_schema_validators(max_items_schema, {})

max_items_validator = generate_object_validator(field_validators=max_items_validators)
Beispiel #24
0
from flex.constants import (
    ARRAY,
)
from flex.validation.common import (
    generate_object_validator,
)
from flex.validation.schema import (
    construct_schema_validators,
)


enum_schema = {
    'type': ARRAY,
    'minItems': 1,
}
enum_validators = construct_schema_validators(enum_schema, {})

enum_validator = generate_object_validator(
    field_validators=enum_validators,
)
Beispiel #25
0
 def save_object(self, obj, **kwargs):
     validators = construct_schema_validators(obj, self.context)
     self.object = functools.partial(validate_object, validators=validators)
Beispiel #26
0
from flex.constants import (
    BOOLEAN, )
from flex.validation.common import (
    generate_object_validator, )
from flex.validation.schema import (
    construct_schema_validators, )

read_only_schema = {
    'type': BOOLEAN,
}
read_only_validators = construct_schema_validators(read_only_schema, {})

read_only_validator = generate_object_validator(
    field_validators=read_only_validators, )
Beispiel #27
0
from flex.constants import (
    ARRAY,
    STRING,
)
from flex.validation.common import (
    generate_object_validator, )
from flex.validation.schema import (
    construct_schema_validators, )

required_schema = {
    'type': ARRAY,
    'items': {
        'type': STRING,
    },
    'uniqueItems': True,
}
required_validators = construct_schema_validators(required_schema, {})

required_validator = generate_object_validator(
    field_validators=required_validators, )