def validate_path_to_api_path(path,
                              paths,
                              basePath='',
                              context=None,
                              **kwargs):
    """
    Given a path, find the api_path it matches.
    """
    if context is None:
        context = {}
    try:
        api_path = match_path_to_api_path(
            path_definitions=paths,
            target_path=path,
            base_path=basePath,
            context=context,
        )
    except LookupError as err:
        raise ValidationError(str(err))
    except MultiplePathsFound as err:
        raise ValidationError(str(err))

    return api_path
Ejemplo n.º 2
0
Archivo: ref.py Proyecto: Lookyan/flex
def validate_reference(reference, context, **kwargs):
    try:
        parts = urlparse.urlparse(reference)
        if parts.path:
            from flex.core import load_source
            if parts.path.startswith('/'):
                context = load_source(parts.path)
            elif 'base_path' in kwargs:
                context = load_source(
                    os.path.join(kwargs['base_path'], parts.path))
        jsonpointer.resolve_pointer(context, parts.fragment)
    except jsonpointer.JsonPointerException:
        raise ValidationError(
            MESSAGES['reference']['undefined'].format(reference))
Ejemplo n.º 3
0
def validate_unique_items(value, **kwargs):
    """
    Validator for ARRAY types to enforce that all array items must be unique.
    """
    # we can't just look at the items themselves since 0 and False are treated
    # the same as dictionary keys, and objects aren't hashable.

    counter = collections.Counter((
        json.dumps(v, sort_keys=True) for v in value
    ))
    dupes = [json.loads(v) for v, count in counter.items() if count > 1]
    if dupes:
        raise ValidationError(
            MESSAGES['unique_items']['invalid'].format(
                repr(dupes),
            ),
        )
Ejemplo n.º 4
0
def validate_maximum(value, maximum, is_exclusive, **kwargs):
    """
    Validator function for validating that a value does not violate it's
    maximum allowed value.  This validation can be inclusive, or exclusive of
    the maximum depending on the value of `is_exclusive`.
    """
    if is_exclusive:
        comparison_text = "less than"
        compare_fn = operator.lt
    else:
        comparison_text = "less than or equal to"
        compare_fn = operator.le

    if not compare_fn(value, maximum):
        raise ValidationError(
            MESSAGES['maximum']['invalid'].format(value, comparison_text,
                                                  maximum), )
Ejemplo n.º 5
0
def validate_request_method_to_operation(request_method, path_definition):
    """
    Given a request method, validate that the request method is valid for the
    api path.

    If so, return the operation definition related to this request method.
    """
    try:
        operation_definition = path_definition[request_method]
    except KeyError:
        allowed_methods = set(REQUEST_METHODS).intersection(path_definition.keys())
        raise ValidationError(
            MESSAGES['request']['invalid_method'].format(
                request_method, allowed_methods,
            ),
        )
    return operation_definition
Ejemplo n.º 6
0
def generate_allof_validator(allOf, context, **kwargs):
    if 'resolved_refs' not in context:
        context['resolved_refs'] = []

    unresolved_refs = []
    for ref in allOf:
        if isinstance(ref, dict):
            schema = ref['$ref']
            if schema not in context['resolved_refs']:
                unresolved_refs.append(ref)
                context['resolved_refs'].append(schema)
        else:
            raise ValidationError("allOf must be a list dicts.")

    return functools.partial(validate_allof_anyof,
                             sub_schemas=unresolved_refs,
                             context=context,
                             method=all)
Ejemplo n.º 7
0
def validate_status_code_to_response_definition(response, operation_definition):
    """
    Given a response, validate that the response status code is in the accepted
    status codes defined by this endpoint.

    If so, return the response definition that corresponds to the status code.
    """
    status_code = response.status_code
    operation_responses = operation_definition['responses']
    try:
        response_definition = operation_responses[status_code]
    except KeyError:
        raise ValidationError(
            MESSAGES['response']['invalid_status_code'].format(
                status_code, operation_responses.keys(),
            ),
        )
    return response_definition
Ejemplo n.º 8
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
def validate_status_code_to_response_definition(response, operation_definition):
    """
    Given a response, validate that the response status code is in the accepted
    status codes defined by this endpoint.

    If so, return the response definition that corresponds to the status code.
    """
    status_code = response.status_code
    operation_responses = {str(code): val for code, val
                           in operation_definition['responses'].items()}

    key = status_code
    if key not in operation_responses:
        key = 'default'

    try:
        response_definition = operation_responses[key]
    except KeyError:
        raise ValidationError(
            MESSAGES['response']['invalid_status_code'].format(
                status_code, ', '.join(operation_responses.keys()),
            ),
        )
    return response_definition
Ejemplo n.º 10
0
def validate_pattern(value, regex, **kwargs):
    if not regex.match(value):
        raise ValidationError(
            MESSAGES['pattern']['invalid'].format(value, regex.pattern), )
Ejemplo n.º 11
0
def validate_max_length(value, maxLength, **kwargs):
    if len(value) > maxLength:
        raise ValidationError(
            MESSAGES['max_length']['invalid'].format(maxLength))
Ejemplo n.º 12
0
def validate_min_length(value, minLength, **kwargs):
    if len(value) < minLength:
        raise ValidationError(
            MESSAGES['min_length']['invalid'].format(minLength))
Ejemplo n.º 13
0
def date_time_format_validator(value, **kwargs):
    if not strict_rfc3339.validate_rfc3339(value):
        raise ValidationError(MESSAGES['format']['invalid_datetime'].format(value))
Ejemplo n.º 14
0
def date_time_format_validator(value, **kwargs):
    try:
        iso8601.parse_date(value)
    except iso8601.ParseError:
        raise ValidationError(
            MESSAGES['format']['invalid_datetime'].format(value))
Ejemplo n.º 15
0
def validate_items_required_if_type_arraw(type_, items, **kwargs):
    types = pluralize(type_)
    if ARRAY in types and items is EMPTY:
        raise ValidationError(MESSAGES['required']['required'])
Ejemplo n.º 16
0
def validate_type_for_max_length(type_, maxLength, **kwargs):
    types = pluralize(type_)

    if not set(types).intersection((STRING, )):
        raise ValidationError(
            MESSAGES['type']['invalid_type_for_max_length'], )
Ejemplo n.º 17
0
def validate_type(_type, **kwargs):
    if _type not in ALLOWED_TYPES:
        raise ValidationError(MESSAGES['enum']['invalid'].format(_type, ALLOWED_TYPES))
Ejemplo n.º 18
0
def int64_validator(value, **kwargs):
    num_bits = number_of_bits(value)
    if num_bits > 64:
        raise ValidationError(MESSAGES['format']['too_many_bits'].format(
            value, num_bits, 64))
Ejemplo n.º 19
0
Archivo: in_.py Proyecto: djta/5GCORE-1
def validate_body_parameters_must_include_a_schema(in_, schema, **kwargs):
    if in_ == BODY:
        if schema is EMPTY:
            raise ValidationError(
                MESSAGES['schema']['body_parameters_must_include_a_schema'])
Ejemplo n.º 20
0
def int32_validator(value, **kwargs):
    if value < -2147483648 or value > 2147483647:
        raise ValidationError(MESSAGES['format']['invalid_int'].format(
            value, 32))
Ejemplo n.º 21
0
def uuid_format_validator(value, **kwargs):
    if not UUID_PATTERN.match(value):
        raise ValidationError(MESSAGES['format']['invalid_uuid'].format(value))
Ejemplo n.º 22
0
def date_format_validator(value, **kwargs):
    try:
        datetime.datetime.strptime(value, '%Y-%m-%d')
    except ValueError:
        raise ValidationError(MESSAGES['format']['invalid_date'].format(value))
Ejemplo n.º 23
0
def validate_enum(value, options, **kwargs):
    if not any(deep_equal(value, option) for option in options):
        raise ValidationError(MESSAGES['enum']['invalid'].format(
            value,
            options,
        ))
Ejemplo n.º 24
0
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'], )
Ejemplo n.º 25
0
def int64_validator(value, **kwargs):
    if value < -9223372036854775808 or value > 9223372036854775807:
        raise ValidationError(MESSAGES['format']['invalid_int'].format(
            value, 64))
Ejemplo n.º 26
0
def email_validator(value, **kwargs):
    if not validate_email.validate_email(value):
        raise ValidationError(
            MESSAGES['format']['invalid_email'].format(value))
Ejemplo n.º 27
0
Archivo: in_.py Proyecto: djta/5GCORE-1
def validate_path_parameters_must_be_required(in_, required, **kwargs):
    if in_ == PATH:
        if required is not True:
            raise ValidationError(
                MESSAGES['required']['path_parameters_must_be_required'])
Ejemplo n.º 28
0
def validate_required(value, **kwargs):
    if value is EMPTY:
        raise ValidationError(MESSAGES['required']['required'])
Ejemplo n.º 29
0
Archivo: in_.py Proyecto: djta/5GCORE-1
def validate_type_declared_for_non_body_parameters(in_, type_, **kwargs):
    if in_ != BODY:
        if type_ is EMPTY:
            raise ValidationError(
                MESSAGES['type']['non_body_parameters_must_declare_a_type'])
Ejemplo n.º 30
0
def validate_mimetype(values, **kwargs):
    for value in values:
        if not re.match(MIMETYPE_PATTERN, value):
            raise ValidationError(
                MESSAGES['mimetype']['invalid'].format(value), )