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
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))
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), ), )
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), )
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
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)
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
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
def validate_pattern(value, regex, **kwargs): if not regex.match(value): raise ValidationError( MESSAGES['pattern']['invalid'].format(value, regex.pattern), )
def validate_max_length(value, maxLength, **kwargs): if len(value) > maxLength: raise ValidationError( MESSAGES['max_length']['invalid'].format(maxLength))
def validate_min_length(value, minLength, **kwargs): if len(value) < minLength: raise ValidationError( MESSAGES['min_length']['invalid'].format(minLength))
def date_time_format_validator(value, **kwargs): if not strict_rfc3339.validate_rfc3339(value): raise ValidationError(MESSAGES['format']['invalid_datetime'].format(value))
def date_time_format_validator(value, **kwargs): try: iso8601.parse_date(value) except iso8601.ParseError: raise ValidationError( MESSAGES['format']['invalid_datetime'].format(value))
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'])
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'], )
def validate_type(_type, **kwargs): if _type not in ALLOWED_TYPES: raise ValidationError(MESSAGES['enum']['invalid'].format(_type, ALLOWED_TYPES))
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))
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'])
def int32_validator(value, **kwargs): if value < -2147483648 or value > 2147483647: raise ValidationError(MESSAGES['format']['invalid_int'].format( value, 32))
def uuid_format_validator(value, **kwargs): if not UUID_PATTERN.match(value): raise ValidationError(MESSAGES['format']['invalid_uuid'].format(value))
def date_format_validator(value, **kwargs): try: datetime.datetime.strptime(value, '%Y-%m-%d') except ValueError: raise ValidationError(MESSAGES['format']['invalid_date'].format(value))
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, ))
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'], )
def int64_validator(value, **kwargs): if value < -9223372036854775808 or value > 9223372036854775807: raise ValidationError(MESSAGES['format']['invalid_int'].format( value, 64))
def email_validator(value, **kwargs): if not validate_email.validate_email(value): raise ValidationError( MESSAGES['format']['invalid_email'].format(value))
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'])
def validate_required(value, **kwargs): if value is EMPTY: raise ValidationError(MESSAGES['required']['required'])
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'])
def validate_mimetype(values, **kwargs): for value in values: if not re.match(MIMETYPE_PATTERN, value): raise ValidationError( MESSAGES['mimetype']['invalid'].format(value), )