Python jsonschema.SchemaError() Examples

The following are 23 code examples of jsonschema.SchemaError(). 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 jsonschema , or try the search function .
Example #1
Source File: indicators.py    From watcher with Apache License 2.0 6 votes vote down vote up
def validate(cls, solution):
        """Validate the given solution

        :raises: :py:class:`~.InvalidIndicatorValue` when the validation fails
        """
        indicator = cls()
        value = None
        try:
            value = getattr(solution, indicator.name)
            jsonschema.validate(value, cls.schema)
        except (SchemaError, ValidationError) as exc:
            LOG.exception(exc)
            raise
        except Exception as exc:
            LOG.exception(exc)
            raise exception.InvalidIndicatorValue(
                name=indicator.name, value=value, spec_type=type(indicator)) 
Example #2
Source File: schemas_are_valid_json.py    From metadata-schema with Apache License 2.0 6 votes vote down vote up
def get_validator(filename, base_uri=''):
    """Load schema from JSON file;
    Check whether it's a valid schema;
    Return a Draft4Validator object.
    Optionally specify a base URI for relative path
    resolution of JSON pointers (This is especially useful
    for local resolution via base_uri of form file://{some_path}/)
    """

    schema = get_json_from_file(filename)
    try:
        # Check schema via class method call. Works, despite IDE complaining
        Draft4Validator.check_schema(schema)
        print("Schema %s is valid JSON" % filename)
    except SchemaError:
        raise
    if base_uri:
        resolver = RefResolver(base_uri=base_uri,
                               referrer=filename)
    else:
        resolver = None
    return Draft4Validator(schema=schema,
                           resolver=resolver) 
Example #3
Source File: validation.py    From cjio with MIT License 5 votes vote down vote up
def validate_against_schema(j, js):
    isValid = True
    es = []
    #-- lazy validation to catch as many as possible
    myvalidator = jsonschema.Draft4Validator(js, format_checker=jsonschema.FormatChecker())
    for err in sorted(myvalidator.iter_errors(j), key=str):
        isValid = False
        es.append(err.message)
    return (isValid, es)

    # try:
    #     jsonschema.Draft4Validator(js, format_checker=jsonschema.FormatChecker()).validate(j)
    # except jsonschema.ValidationError as e:
    #     raise Exception(e.message)
    #     return False
    # except jsonschema.SchemaError as e:
    #     raise Exception(e.message)
    #     return False
    
    # try:
    #     jsonschema.validate(j, js, format_checker=jsonschema.FormatChecker())
    # except jsonschema.ValidationError as e:
    #     raise Exception(e.message)
    #     return False
    # except jsonschema.SchemaError as e:
    #     raise Exception(e.message)
    #     return False 
Example #4
Source File: formats.py    From awscfncli with MIT License 5 votes vote down vote up
def validate(self, config):
        schema = load_schema(str(self.VERSION))
        jsonschema.validate(config, schema)

        if have_parameter_reference_pattern(config):
            raise jsonschema.SchemaError(
                'Do not support parameter reference in config version <= 2') 
Example #5
Source File: json_schema.py    From pan-fca with Apache License 2.0 5 votes vote down vote up
def validate_schema(schema, data):
    try:
        validate(data, schema, format_checker=FormatChecker())
    except ValidationError as e:
        return (False, "ValidationError: {0}".format(e.message))
    except SchemaError as e:
        return (False, "SchemaError: {0}".format(e.message))
    except Exception as e:
        return (False, "UnknownError: {0}".format(e.message))
    return (True, '') 
Example #6
Source File: request.py    From trains with Apache License 2.0 5 votes vote down vote up
def validate(self):
        if not self._validate_requests or self._allow_raw_requests:
            return
        for i, req in enumerate(self.requests):
            try:
                req.validate()
            except (jsonschema.SchemaError, jsonschema.ValidationError,
                    jsonschema.FormatError, jsonschema.RefResolutionError) as e:
                raise Exception('Validation error in batch item #%d: %s' % (i, str(e))) 
Example #7
Source File: request.py    From trains-agent with Apache License 2.0 5 votes vote down vote up
def validate(self):
        if not self._validate_requests or self._allow_raw_requests:
            return
        for i, req in enumerate(self.requests):
            try:
                req.validate()
            except (jsonschema.SchemaError, jsonschema.ValidationError,
                    jsonschema.FormatError, jsonschema.RefResolutionError) as e:
                raise Exception('Validation error in batch item #%d: %s' % (i, str(e))) 
Example #8
Source File: applications.py    From zoe with Apache License 2.0 5 votes vote down vote up
def app_validate(data):
    """
    Validates an application description, making sure all required fields are present and of the correct type.
    If the description is not valid, an InvalidApplicationDescription exception is thrown.
    Uses a JSON schema definition.

    :param data: an open file descriptor containing JSON data
    :return: None if the application description is correct
    """

    schema = json.load(open('schemas/app_description_schema.json', 'r'))
    try:
        jsonschema.validate(data, schema)
    except jsonschema.ValidationError as e:
        raise InvalidApplicationDescription(str(e))
    except jsonschema.SchemaError:
        log.exception('BUG: invalid schema for application descriptions')
        raise ZoeLibException('BUG: invalid schema for application descriptions')

    # Start non-schema, semantic checks
    if data['version'] != zoe_lib.version.ZOE_APPLICATION_FORMAT_VERSION:
        raise InvalidApplicationDescription('Application description version mismatch (expected: {}, found: {}'.format(zoe_lib.version.ZOE_APPLICATION_FORMAT_VERSION, data['version']))

    found_monitor = False
    for service in data['services']:
        if service['monitor']:
            found_monitor = True

        service['resources']['memory']['max'] = zoe_lib.config.get_conf().max_memory_limit * (1024 ** 3)
        if service['resources']['memory']['min'] is not None and service['resources']['memory']['min'] > service['resources']['memory']['max']:
            raise InvalidApplicationDescription(msg='service {} tries to reserve more memory than the administrative limit'.format(service['name']))

        if service['resources']['cores']['min'] is None:
            service['resources']['cores']['min'] = 0.1

    if not found_monitor:
        raise InvalidApplicationDescription(msg="at least one process should have the monitor property set to true") 
Example #9
Source File: test_eventlog.py    From binderhub with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_register_invalid():
    """
    Test registering invalid schemas fails
    """
    el = EventLog()
    with pytest.raises(jsonschema.SchemaError):
        el.register_schema({
            # Totally invalid
            'properties': True
        })

    with pytest.raises(ValueError):
        el.register_schema({
            'properties': {}
        })

    with pytest.raises(ValueError):
        el.register_schema({
            '$id': 'something',
            '$version': 1,
            'properties': {
                'timestamp': {
                    'type': 'string'
                }
            }
        }) 
Example #10
Source File: test_config.py    From nmt-wizard-docker with MIT License 5 votes vote down vote up
def test_inference_options_invalid_shema():
    opt = copy.deepcopy(_test_inference_options)
    opt["json_schema"]["type"] = "objects"
    with pytest.raises(jsonschema.SchemaError):
        config.validate_inference_options(opt, _test_config) 
Example #11
Source File: core.py    From notifiers with MIT License 5 votes vote down vote up
def _validate_schema(self):
        """
        Validates provider schema for syntax issues. Raises :class:`~notifiers.exceptions.SchemaError` if relevant

        :raises: :class:`~notifiers.exceptions.SchemaError`
        """
        try:
            log.debug("validating provider schema")
            self.validator.check_schema(self.schema)
        except jsonschema.SchemaError as e:
            raise SchemaError(
                schema_error=e.message, provider=self.name, data=self.schema
            ) 
Example #12
Source File: test_register_schema.py    From telemetry with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_register_invalid_schema():
    """
    Invalid JSON Schemas should fail registration
    """
    el = EventLog()
    with pytest.raises(jsonschema.SchemaError):
        el.register_schema({
            # Totally invalid
            'properties': True
        }) 
Example #13
Source File: validate.py    From jack with MIT License 5 votes vote down vote up
def main(arg1, arg2):
    with open(arg1) as f:
        data = json.load(f)

    with open(arg2) as f:
        schema = json.load(f)

    try:
        jsonschema.validate(data, schema)
        return 'JSON successfully validated.'
    except jsonschema.ValidationError as e:
        return e.message
    except jsonschema.SchemaError as e:
        return e 
Example #14
Source File: val.py    From AIT-Core with MIT License 5 votes vote down vote up
def schema_val(self, messages=None):
        "Perform validation with processed YAML and Schema"
        self._ymlproc = YAMLProcessor(self._ymlfile)
        self._schemaproc = SchemaProcessor(self._schemafile)
        valid = True

        log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self._ymlfile, self._schemafile)

        # Make sure the yml and schema have been loaded
        if self._ymlproc.loaded and self._schemaproc.loaded:
            # Load all of the yaml documents. Could be more than one in the same YAML file.
            for docnum, data in enumerate(yaml.load_all(self._ymlproc.data, Loader=yaml.Loader)):

                # Since YAML allows integer keys but JSON does not, we need to first
                # dump the data as a JSON string to encode all of the potential integers
                # as strings, and then read it back out into the YAML format. Kind of
                # a clunky workaround but it works as expected.
                data = yaml.load(json.dumps(data), Loader=yaml.Loader)

                # Now we want to get a validator ready
                v = jsonschema.Draft4Validator(self._schemaproc.data)

                # Loop through the errors (if any) and set valid = False if any are found
                # Display the error message
                for error in sorted(v.iter_errors(data)):
                    msg = "Schema-based validation failed for YAML file '" + self._ymlfile + "'"
                    self.ehandler.process(docnum, self._ymlproc.doclines, error, messages)
                    valid = False

                if not valid:
                    log.error(msg)

        elif not self._ymlproc.loaded:
            raise util.YAMLError("YAML must be loaded in order to validate.")
        elif not self._schemaproc.loaded:
            raise jsonschema.SchemaError("Schema must be loaded in order to validate.")

        log.debug("END: Schema-based validation complete for '%s'", self._ymlfile)
        return valid 
Example #15
Source File: val.py    From AIT-Core with MIT License 5 votes vote down vote up
def load(self, schemafile=None):
        """Load and process the schema file"""
        if schemafile is not None:
            self._schemafile = schemafile

        try:
            self.data = json.load(open(self._schemafile))
        except (IOError, ValueError) as e:
            msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
            raise jsonschema.SchemaError(msg)

        self.loaded = True 
Example #16
Source File: test_val.py    From AIT-Core with MIT License 5 votes vote down vote up
def test_schema_load_failure_no_json_object(self):
        test_file_path = '/tmp/test.json'
        open(test_file_path, 'w').close()

        schemaproc = val.SchemaProcessor()

        nose.tools.assert_raises(
            jsonschema.SchemaError,
            schemaproc.load, test_file_path
        )

        os.remove(test_file_path) 
Example #17
Source File: test_val.py    From AIT-Core with MIT License 5 votes vote down vote up
def test_schema_load_failure_bad_file(self):
        """ Test Exception raise on not existent file load. """
        schemaproc = val.SchemaProcessor()

        schema = os.path.join('not', 'a', 'valid', 'path.json')
        nose.tools.assert_raises(
            jsonschema.SchemaError,
            schemaproc.load, schema
        ) 
Example #18
Source File: validate.py    From tcex with Apache License 2.0 5 votes vote down vote up
def check_layout_json(self):
        """Check all layout.json files for valid schema."""
        # the install.json files can't be validates if the schema file is not present
        layout_json_file = 'layout.json'
        if self.layout_json_schema is None or not os.path.isfile(layout_json_file):
            return

        error = None
        status = True
        try:
            # loading explicitly here to keep all error catching in this file
            with open(layout_json_file) as fh:
                data = json.loads(fh.read())
            validate(data, self.layout_json_schema)
        except SchemaError as e:
            status = False
            error = e
        except ValidationError as e:
            status = False
            error = e.message
        except ValueError:
            # any JSON decode error will be caught during syntax validation
            return

        # update validation data for module
        self.validation_data['schema'].append({'filename': layout_json_file, 'status': status})

        if error:
            # update validation data errors
            self.validation_data['errors'].append(
                f'Schema validation failed for {layout_json_file} ({error}).'
            )
        else:
            self.check_layout_params() 
Example #19
Source File: validate.py    From tcex with Apache License 2.0 5 votes vote down vote up
def check_install_json(self):
        """Check all install.json files for valid schema."""
        if self.install_json_schema is None:
            return

        contents = os.listdir(self.app_path)
        if self.args.install_json is not None:
            contents = [self.args.install_json]

        for install_json in sorted(contents):
            # skip files that are not install.json files
            if 'install.json' not in install_json:
                continue

            error = None
            status = True

            try:
                # loading explicitly here to keep all error catching in this file
                with open(install_json) as fh:
                    data = json.loads(fh.read())
                validate(data, self.install_json_schema)
            except SchemaError as e:
                status = False
                error = e
            except ValidationError as e:
                status = False
                error = e.message
            except ValueError:
                # any JSON decode error will be caught during syntax validation
                return

            if error:
                # update validation data errors
                self.validation_data['errors'].append(
                    f'Schema validation failed for {install_json} ({error}).'
                )

            # update validation data for module
            self.validation_data['schema'].append({'filename': install_json, 'status': status}) 
Example #20
Source File: validate.py    From armada with Apache License 2.0 4 votes vote down vote up
def validate_armada_document(document):
    """Validates a document ingested by Armada by subjecting it to JSON schema
    validation.

    :param dict dictionary: The document to validate.

    :returns: A tuple of (bool, list[dict]) where the first value
        indicates whether the validation succeeded or failed and
        the second value is the validation details with a minimum
        keyset of (message(str), error(bool))
    :rtype: tuple.
    :raises TypeError: If ``document`` is not of type ``dict``.

    """
    if not isinstance(document, dict):
        raise TypeError(
            'The provided input "%s" must be a dictionary.' % document)

    schema = document.get('schema', '<missing>')
    document_name = document.get('metadata', {}).get('name', None)
    details = []
    LOG.debug('Validating document [%s] %s', schema, document_name)

    schema_info = sch.get_schema_info(schema)
    if schema_info:
        try:
            validator = jsonschema.Draft4Validator(schema_info.data)
            for error in validator.iter_errors(document.get('data')):
                error_message = "Invalid document [%s] %s: %s." % \
                    (schema, document_name, error.message)
                vmsg = ValidationMessage(
                    message=error_message,
                    error=True,
                    name='ARM100',
                    level='Error',
                    schema=schema,
                    doc_name=document_name)
                LOG.info('ValidationMessage: %s', vmsg.get_output_json())
                details.append(vmsg.get_output())
        except jsonschema.SchemaError as e:
            error_message = (
                'The built-in Armada JSON schema %s is invalid. '
                'Details: %s.' % (e.schema, e.message))
            vmsg = ValidationMessage(
                message=error_message,
                error=True,
                name='ARM000',
                level='Error',
                diagnostic='Armada is misconfigured.')
            LOG.error('ValidationMessage: %s', vmsg.get_output_json())
            details.append(vmsg.get_output())

    if len([x for x in details if x.get('error', False)]) > 0:
        return False, details

    return True, details 
Example #21
Source File: yaml.py    From osbs-client with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def read_yaml(yaml_data, schema, package=None):
    """
    :param yaml_data: string, yaml content
    :param schema: string, file path to the JSON schema
    :package: string, package name containing the schema
    """
    package = package or 'osbs'
    try:
        resource = resource_stream(package, schema)
        schema = codecs.getreader('utf-8')(resource)
    except (ImportError):
        logger.error('Unable to find package %s', package)
        raise
    except (IOError, TypeError):
        logger.error('unable to extract JSON schema, cannot validate')
        raise

    try:
        schema = json.load(schema)
    except ValueError:
        logger.error('unable to decode JSON schema, cannot validate')
        raise
    data = yaml.safe_load(yaml_data)
    validator = jsonschema.Draft4Validator(schema=schema)
    try:
        jsonschema.Draft4Validator.check_schema(schema)
        validator.validate(data)
    except jsonschema.SchemaError:
        logger.error('invalid schema, cannot validate')
        raise
    except jsonschema.ValidationError as exc:
        logger.debug("schema validation error: %s", exc)

        exc_message = get_error_message(exc)

        for error in validator.iter_errors(data):
            error_message = get_error_message(error)

            logger.debug("validation error: %s", error_message)

        raise OsbsValidationException(exc_message)

    return data 
Example #22
Source File: validation.py    From amivapi with GNU Affero General Public License v3.0 4 votes vote down vote up
def _validate_json_schema(self, enabled, field, value):
        """Validate a json schema[1] string.

        1.  Is the string valid JSON?
        2.  Does it satisfy our restrictions for jsonschemas?
        3.  Is it a valid json-schema?

        Args:
            field (string): field name
            value: field value

        1: https://json-schema.org

        The rule's arguments are validated against this schema:
        {'type': 'boolean'}
        """
        if not enabled:
            return

        try:
            json_data = json.loads(value)
        except json.JSONDecodeError as error:
            self._error(field,
                        "Invalid json, parsing failed with exception: %s"
                        % error)
            return

        # validate if these fields are included exactly as given
        # (we, e.g., always require objects so UI can rely on this)
        enforced_fields = {
            '$schema': 'http://json-schema.org/draft-04/schema#',
            'type': 'object',
            'additionalProperties': False
        }

        for key, val in enforced_fields.items():
            if key not in json_data or json_data[key] != val:
                self._error(field,
                            "'%s' is required to be set to '%s'"
                            % (key, val))

        # now check if it is entirely valid jsonschema
        validator = Draft4Validator(json_data)
        # by default, jsonschema specification allows unknown properties
        # We do not allow these.
        validator.META_SCHEMA['additionalProperties'] = False

        try:
            validator.check_schema(json_data)
        except SchemaError as error:
            self._error(field, "does not contain a valid schema: %s"
                        % error)

    # Eve doesn't handle time zones properly. It's always UTC but sometimes
    # the timezone is included, sometimes it isn't. 
Example #23
Source File: IS0501Test.py    From nmos-testing with Apache License 2.0 4 votes vote down vote up
def check_staged_complies_with_constraints(self, port, portList):
        """Check that the staged endpoint is using parameters that meet
        the contents of the /constraints endpoint"""
        for myPort in portList:
            dest = "single/" + port + "s/" + myPort + "/staged/"
            valid, response = self.is05_utils.checkCleanRequestJSON("GET", dest)
            file_suffix = None
            if self.transport_types[myPort] == "urn:x-nmos:transport:rtp":
                file_suffix = "_transport_params_rtp.json"
            elif self.transport_types[myPort] == "urn:x-nmos:transport:mqtt":
                file_suffix = "_transport_params_mqtt.json"
            elif self.transport_types[myPort] == "urn:x-nmos:transport:websocket":
                file_suffix = "_transport_params_websocket.json"
            if valid:
                try:
                    schema_items = load_resolved_schema(self.apis[CONN_API_KEY]["spec_path"],
                                                        port + file_suffix)
                    schema = {
                        "$schema": "http://json-schema.org/draft-04/schema#",
                        "type": "array",
                        "items": schema_items
                    }
                except FileNotFoundError:
                    schema = load_resolved_schema(self.apis[CONN_API_KEY]["spec_path"],
                                                  "v1.0_" + port + file_suffix)
                url = "single/" + port + "s/" + myPort + "/constraints/"
                constraints_valid, constraints_response = self.is05_utils.checkCleanRequestJSON("GET", url)

                if constraints_valid:
                    count = 0
                    try:
                        for params in response['transport_params']:
                            try:
                                schema.update(constraints_response[count])
                            except IndexError:
                                return False, "Number of 'legs' in constraints does not match the number in " \
                                              "transport_params"
                            schema["items"]["$schema"] = "http://json-schema.org/draft-04/schema#"
                            try:
                                self.validate_schema(params, schema["items"])
                            except ValidationError as e:
                                return False, "Staged endpoint does not comply with constraints in leg {}: " \
                                              "{}".format(count, str(e))
                            except SchemaError as e:
                                return False, "Invalid schema resulted from combining constraints in leg {}: {}".format(
                                    count,
                                    str(e))
                            count = count + 1
                    except KeyError:
                        return False, "Expected 'transport_params' key in '/staged'."
                else:
                    return False, constraints_response
            else:
                return False, response
        return True, ""