Realiza validaciones sin usar el jsonschema.

    En esta función se agregan bloques de código en python que realizan
    validaciones complicadas o imposibles de especificar usando jsonschema.
494654
def iter_custom_errors(catalog):
    

    try:
        # chequea que no se repiten los ids de la taxonomía específica
        if "themeTaxonomy" in catalog:
            theme_ids = [theme["id"] for theme in catalog["themeTaxonomy"]]
            dups = _find_dups(theme_ids)
            if len(dups) > 0:
                yield ce.ThemeIdRepeated(dups)

        # chequea que un dataset no use un theme que no exista en la taxonomía
        # TODO: hay que implementarlo

        # chequea que un dataset no use theme con id esté repetido en taxonomía
        # TODO: hay que implementarlo

        # chequea que la extensión de fileName, downloadURL y format sean
        # consistentes
        for dataset_idx, dataset in enumerate(catalog["dataset"]):
            for distribution_idx, distribution in enumerate(
                    dataset["distribution"]):
                for attribute in ['downloadURL', 'fileName']:
                    if not format_matches_extension(distribution, attribute):
                        yield ce.ExtensionError(dataset_idx, distribution_idx,
                                                distribution, attribute)

        # chequea que no haya duplicados en los downloadURL de las
        # distribuciones
        # urls = []
        # for dataset in catalog["dataset"]:
        #     urls += [distribution['downloadURL']
        #              for distribution in dataset['distribution']
        #              if distribution.get('downloadURL')]
        # dups = _find_dups(urls)
        # if len(dups) > 0:
        #     yield ce.DownloadURLRepetitionError(dups)

        # chequea que las URLs de las distribuciones estén operativas
        # hay que revisar
        # for distribution in catalog.distributions:
        #     url = distribution.get("downloadURL")
        #     status_code = requests.head(url).status_code
        #     if status_code != 200:
        #         yield ce.DownloadURLBrokenError(
        #             distribution.get("identifier"), url, status_code)

    except Exception:
        logger.exception("Error de validación.")
1128821
def validate_api_call(schema, raw_request, raw_response):
    
    request = normalize_request(raw_request)

    with ErrorDict() as errors:
        try:
            validate_request(
                request=request,
                schema=schema,
            )
        except ValidationError as err:
            errors['request'].add_error(err.messages or getattr(err, 'detail'))
            return

        response = normalize_response(raw_response, raw_request)

        try:
            validate_response(
                response=response,
                request_method=request.method,
                schema=schema
            )
        except ValidationError as err:
            errors['response'].add_error(err.messages or getattr(err, 'detail'))
1162038
def validate(self):
        
        validator = Draft7Validator(self.SCHEMA)

        errors = set()  # make errors a set to avoid duplicates

        for error in validator.iter_errors(self.serialize()):
            errors.add('.'.join(
                list(map(str, error.path)) + [error.message]
            ))

        if errors:
            raise JSONValidationException(type(self).__name__, errors)
1177133
function JSONSchema () {
  var self = this;

  self.klass = JSONSchema;
  self.klass.super_.apply(self, arguments);

  self.engine = require('json-schema');
}
1206309
public function validateSchema()
    {
        $meta_schema_validator = new SchemaValidator();
        $json_loader = new JsonLoader();

        // we have to check if we use a prefix
        $meta_json = file_get_contents(__DIR__.'/../../../data/MetaSchema.json');
        $meta_json = str_replace('#', $this->prefix, $meta_json);

        // we validate the schema using the meta schema, defining the structure of our schema
        $meta_schema_validator->validate($json_loader->load($meta_json), $this->schema);

        return true;
    }
1366050
def _validate_string(self, input_string, path_to_root, object_title=''):

        '''
            
        '''

        rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root)
        input_criteria = self.keyMap[rules_path_to_root]
        error_dict = {
            'object_title': object_title,
            'model_schema': self.schema,
            'input_criteria': input_criteria,
            'failed_test': 'value_datatype',
            'input_path': path_to_root,
            'error_value': input_string,
            'error_code': 4001
        }
        if 'byte_data' in input_criteria.keys():
            if input_criteria['byte_data']:
                error_dict['failed_test'] = 'byte_data'
                error_dict['error_code'] = 4011
                try:
                    decoded_bytes = b64decode(input_string)
                except:
                    raise InputValidationError(error_dict)
                if not isinstance(decoded_bytes, bytes):
                    raise InputValidationError(error_dict)
        if 'min_value' in input_criteria.keys():
            if input_string < input_criteria['min_value']:
                error_dict['failed_test'] = 'min_value'
                error_dict['error_code'] = 4022
                raise InputValidationError(error_dict)
        if 'max_value' in input_criteria.keys():
            if input_string > input_criteria['max_value']:
                error_dict['failed_test'] = 'max_value'
                error_dict['error_code'] = 4023
                raise InputValidationError(error_dict)
        if 'greater_than' in input_criteria.keys():
            if input_string <= input_criteria['greater_than']:
                error_dict['failed_test'] = 'greater_than'
                error_dict['error_code'] = 4024
                raise InputValidationError(error_dict)
        if 'less_than' in input_criteria.keys():
            if input_string >= input_criteria['less_than']:
                error_dict['failed_test'] = 'less_than'
                error_dict['error_code'] = 4025
                raise InputValidationError(error_dict)
        if 'equal_to' in input_criteria.keys():
            if input_string != input_criteria['equal_to']:
                error_dict['failed_test'] = 'equal_to'
                error_dict['error_code'] = 4026
                raise InputValidationError(error_dict)
        if 'min_length' in input_criteria.keys():
            if len(input_string) < input_criteria['min_length']:
                error_dict['failed_test'] = 'min_length'
                error_dict['error_code'] = 4012
                raise InputValidationError(error_dict)
        if 'max_length' in input_criteria.keys():
            if len(input_string) > input_criteria['max_length']:
                error_dict['failed_test'] = 'max_length'
                error_dict['error_code'] = 4013
                raise InputValidationError(error_dict)
        if 'must_not_contain' in input_criteria.keys():
            for regex in input_criteria['must_not_contain']:
                regex_pattern = re.compile(regex)
                if regex_pattern.findall(input_string):
                    error_dict['failed_test'] = 'must_not_contain'
                    error_dict['error_code'] = 4014
                    raise InputValidationError(error_dict)
        if 'must_contain' in input_criteria.keys():
            for regex in input_criteria['must_contain']:
                regex_pattern = re.compile(regex)
                if not regex_pattern.findall(input_string):
                    error_dict['failed_test'] = 'must_contain'
                    error_dict['error_code'] = 4015
                    raise InputValidationError(error_dict)
        if 'contains_either' in input_criteria.keys():
            regex_match = False
            for regex in input_criteria['contains_either']:
                regex_pattern = re.compile(regex)
                if regex_pattern.findall(input_string):
                    regex_match = True
            if not regex_match:
                error_dict['failed_test'] = 'contains_either'
                error_dict['error_code'] = 4016
                raise InputValidationError(error_dict)
        if 'discrete_values' in input_criteria.keys():
            if input_string not in input_criteria['discrete_values']:
                error_dict['failed_test'] = 'discrete_values'
                error_dict['error_code'] = 4041
                raise InputValidationError(error_dict)
        if 'excluded_values' in input_criteria.keys():
            if input_string in input_criteria['excluded_values']:
                error_dict['failed_test'] = 'excluded_values'
                error_dict['error_code'] = 4042
                raise InputValidationError(error_dict)

    # TODO: validate string against identical to reference

    # TODO: run lambda function and call validation url

        return input_string
609267
def validation_schema(name):
    """"""
    schemas = {
        'processor': 'processSchema.json',
        'descriptor': 'descriptorSchema.json',
        'field': 'fieldSchema.json',
        'type': 'typeSchema.json',
    }

    if name not in schemas:
        raise ValueError()

    field_schema_file = finders.find('flow/{}'.format(schemas['field']), all=True)[0]
    with open(field_schema_file, 'r') as fn:
        field_schema = fn.read()

    if name == 'field':
        return json.loads(field_schema.replace('{{PARENT}}', ''))

    schema_file = finders.find('flow/{}'.format(schemas[name]), all=True)[0]
    with open(schema_file, 'r') as fn:
        schema = fn.read()

    return json.loads(schema.replace('{{FIELD}}', field_schema).replace('{{PARENT}}', '/field'))
1060243
function validateSchema (api) {
  // Choose the appropriate schema (Swagger or OpenAPI)
  var schema = api.swagger
    ? require("swagger-schema-official/schema.json")
    : require("openapi-schema-validation/schema/openapi-3.0.json");

  var isValid = ZSchema.validate(api, schema);

  if (!isValid) {
    var err = ZSchema.getLastError();
    var message = "Swagger schema validation failed. \n" + formatZSchemaError(err.details);
    throw ono.syntax(err, { details: err.details }, message);
  }
}
821354
protected function performValidation()
    {
        // All the fixed fields declared above are objects that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$.
        foreach (array_keys($this->attributes()) as $attribute) {
            if (is_array($this->$attribute)) {
                foreach ($this->$attribute as $k => $v) {
                    if (!preg_match('~^[a-zA-Z0-9\.\-_]+$~', $k)) {
                        $this->addError("Invalid key '$k' used in Components Object for attribute '$attribute', does not match ^[a-zA-Z0-9\.\-_]+\$.");
                    }
                }
            }
        }
    }
1258332
function validateJSONResponse(resp, result_schema) {

   const ajv = new Ajv();
   if (result_schema) {
      try {
         const valid = ajv.validate(result_schema, resp);
         assert(valid);
         return resp;
      }
      catch(e) {
         try {
            // error message
            const valid = ajv.validate(CORE_ERROR_SCHEMA, resp);
            assert(valid);
            return resp;
         }
         catch(e2) {
            console.log("Failed to validate with desired schema");
            console.log(e.stack);
            console.log("Failed to validate with error schema");
            console.log(e2.stack);
            console.log("Desired schema:");
            console.log(result_schema);
            console.log("Parsed message:");
            console.log(resp);
            throw new Error("Invalid core message");
         }
      }
   }
   else {
      return resp;
   }
}
705332
protected function validateSchema()
    {
        $schemaPath = $this->getOption('schemaPath');

        if ($schemaPath === null) {
            return;
        }

        $schemaData = json_decode(file_get_contents($schemaPath));

        if (!class_exists('\\JsonSchema\\Validator')) {
            throw new \RuntimeException(
                'If you want to validate a JSON schema, you must require package "justinrainbow/json-schema"-'
            );
        }

        $validator = new \JsonSchema\Validator();
        $validator->check($this->getContents(), $schemaData);

        if (!$validator->isValid()) {
            $errors = [];

            foreach ((array) $validator->getErrors() as $error) {
                $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message'];
            }

            throw DecodeException::create($this->getPath(), ['errors' => $errors]);
        }
    }
494406
def validate_json(f):
    """"""
    @wraps(f)
    def wrapper(*args, **kw):
        instance = args[0]
        try:
            if request.get_json() is None:
                ret_dict = instance._create_ret_object(instance.FAILURE,
                                                       None, True,
                                                       instance.MUST_JSON)
                instance.logger.error(instance.MUST_JSON)
                return jsonify(ret_dict), 400
        except BadRequest:
            ret_dict = instance._create_ret_object(instance.FAILURE, None,
                                                   True,
                                                   instance.MUST_JSON)
            instance.logger.error(instance.MUST_JSON)
            return jsonify(ret_dict), 400
        instance.logger.debug("JSON is valid")
        return f(*args, **kw)
    return wrapper
476431
public boolean matchJsonToSchema(JSONObject schema, JSONObject json) throws Exception {
        SchemaLoader.builder()
                 .useDefaults(true)
                 .schemaJson(schema)
                 .build()
                 .load()
                 .build()
                 .validate(json);
        return true;
    }
436759
def validate_yaml_file(schema: dict, yaml_file: Path):
    

    with yaml_file.open() as f:
        data = yaml.load(f)

    jsonschema.validate(data, schema)
1373024
def validate(data, schema, defined_keys=False):
    
    if isinstance(data, dict):
        validator = Validator(data, schema, defined_keys=defined_keys)
        validator.validate()
    else:
        raise TypeError('expected data to be of type dict, but got: %s' % type(data))
550882
def json_validate(schema, resp):
    
    # is this an error?
    try:
        json_validate_error(resp)
    except ValidationError:
        if json_is_exception(resp):
            # got a traceback 
            if BLOCKSTACK_TEST:
                log.error('\n{}'.format(resp['traceback']))

            return {'error': 'Blockstack Core encountered an exception. See `traceback` for details', 'traceback': resp['traceback'], 'http_status': 500}

        if 'error' in resp and 'http_status' not in resp:
            # bad error message
            raise 

        # not an error.
        jsonschema.validate(resp, schema)

    return resp
751503
function validate($value, $key, $fields, $options, $exists, \CharlotteDunois\Validation\Validator $validator) {
        if(!$exists) {
            return false;
        }
        
        $is_string = \is_string($value);
        $is_object = \is_object($value);
        
        if(!$is_string && !$is_object) {
            return 'formvalidator_make_class';
        }
        
        $options = \explode('=', $options);
        $class = \ltrim($options[0], '\\');
        
        if(!empty($options[1]) && $options[1] === 'string' && !$is_string) {
            return 'formvalidator_make_class_stringonly';
        }
        
        if(!empty($options[1]) && $options[1] === 'object' && !$is_object) {
            return 'formvalidator_make_class_objectonly';
        }
        
        if($is_string && !\class_exists($value)) {
            return 'formvalidator_make_class';
        }
        
        if(!\is_a($value, $class, true) && !\is_subclass_of($value, $class, true)) {
            return array('formvalidator_make_class_inheritance', array('{0}' => $class));
        }
        
        return true;
    }