Python jsonschema.SchemaError() Examples

The following are code examples for showing how to use jsonschema.SchemaError(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pywhdfs   Author: yassineazzouz   File: config.py    MIT License 6 votes vote down vote up
def __init__(self, path=None):
      self.path = path or os.getenv('WEBHDFS_CONFIG', self.default_path)
      if osp.exists(self.path):
        try:
          self.config = json.loads(open(self.path).read())
          self.schema = json.loads(resource_string(__name__, 'resources/config_schema.json'))
          #self.schema = open("resources/schema.config").read()
          try:
            js.validate(self.config, self.schema)
          except js.ValidationError as e:
            print e.message
          except js.SchemaError as e:
            print e

        except ParsingError:
          raise HdfsError('Invalid configuration file %r.', self.path)

        _logger.info('Instantiated configuration from %r.', self.path)
      else:
        raise HdfsError('Invalid configuration file %r.', self.path) 
Example 2
Project: shelf   Author: not-nexus   File: utils.py    MIT License 6 votes vote down vote up
def validate_against_schema(schema_path, data):
    """
        Validates data against schema.

        Args:
            schema_path(string)
            data(type outlined schema)

        Raises:
            jsonschema.ValidationError: if data does not match schema
            IOError: if schema_path is invalid
            jsonschema.SchemaError: if schema is flawed
    """
    schema_path = create_path(schema_path)
    with open(schema_path, "r") as file:
        schema = file.read()

    schema = json.loads(schema)
    jsonschema.validate(data, schema) 
Example 3
Project: metadata-schema   Author: HumanCellAtlas   File: schemas_are_valid_json.py    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 4
Project: MDStudio   Author: MD-Studio   File: schema_repository.py    Apache License 2.0 6 votes vote down vote up
def upsert(self, vendor, component, schema, claims):

        try:
            Draft4Validator.check_schema(schema['schema'])
        except SchemaError as e:
            raise SchemaException('Schema does not conform to jsonschema draft 4, ' \
                                  'see http://json-schema.org/ for more info:\n{}\n\n{}'.format(pformat(schema['schema']), e.message))

        schema_str = self.schema_to_string(schema['schema'])
        hash = self.hash_schema(schema_str)
        name = schema['name']
        version = schema['version']
        latest = yield self.find_latest(vendor, component, name, version, schema_str)

        if not latest:
            yield self._upload_new_schema(claims, component, hash, name, schema, schema_str, vendor, version) 
Example 5
Project: osparc-simcore   Author: ITISFoundation   File: test_individual_json_schemas.py    MIT License 6 votes vote down vote up
def test_valid_individual_json_schemas_specs(spec_file_path):
    spec_file_path = Path(spec_file_path)
    specs_dict = load_specs(spec_file_path)

    if is_json_schema(specs_dict):
        # it seems it is a json schema file
        try:
            dummy_instance = {}
            validate(dummy_instance, specs_dict)
        except SchemaError as err:
            # this is not good
            pytest.fail("Failed validating %s: \n %s " % (spec_file_path, err.message))
        except ValidationError:
            # this is good
            return
        else:
            # this is also not good and bad from the validator...
            pytest.fail("Expecting an instance validation error if the schema in {file} was correct".format(file=spec_file_path)) 
Example 6
Project: icetea   Author: ARMmbed   File: TestcaseContainer.py    Apache License 2.0 6 votes vote down vote up
def validate_testcase_metadata(self, testcase):
        """
        Validate tc metadata. Returns True if validation succeeds or False if if fails.

        :param testcase: Bench
        :return: Boolean
        """
        try:
            validate(testcase.config, self._meta_schema)
        except ValidationError as err:
            self.logger.error("Metadata validation failed! Please fix your TC Metadata!")
            self.logger.debug(testcase.config)
            self.logger.error(err)
            return False
        except SchemaError as err:
            self.logger.error("Schema error")
            self.logger.error(err)
            return False
        return True 
Example 7
Project: watcher   Author: openstack   File: indicators.py    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 8
Project: robotframework-jsonvalidator   Author: peterservice-rnd   File: JsonValidator.py    Apache License 2.0 6 votes vote down vote up
def _validate_json(self, checked_json: JsonType, schema: Dict[str, Any]) -> None:
        """ Validate JSON according to JSONSchema

        *Args*:\n
            _checked_json_: validated JSON.
            _schema_: schema that used for validation.
        """
        try:
            jsonschema.validate(checked_json, schema)
        except jsonschema.ValidationError as e:
            print("""Failed validating '{0}'
in schema {1}:
{2}
On instance {3}:
{4}""".format(e.validator,
              list(e.relative_schema_path)[:-1], pprint.pformat(e.schema),
              "[%s]" % "][".join(repr(index) for index in e.absolute_path),
              pprint.pformat(e.instance).encode('utf-8')))
            raise JsonValidatorError("Failed validating json by schema")
        except jsonschema.SchemaError as e:
            raise JsonValidatorError(f'Json-schema error: {e}') 
Example 9
Project: async-pluct   Author: globocom   File: resource.py    MIT License 5 votes vote down vote up
def is_valid(self):
        handlers = {'https': self.session_request_json,
                    'http': self.session_request_json}
        schema = await self.schema.raw_schema
        resolver = RefResolver.from_schema(schema,
                                           handlers=handlers)
        try:
            validate(self.data, schema, resolver=resolver)
        except (SchemaError, ValidationError):
            return False
        return True 
Example 10
Project: telemetry   Author: jupyter   File: test_register_schema.py    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 11
Project: tcex   Author: ThreatConnect-Inc   File: validate.py    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(
                    'Schema validation failed for {} ({}).'.format(install_json, error)
                )

            # update validation data for module
            self.validation_data['schema'].append({'filename': install_json, 'status': status}) 
Example 12
Project: tcex   Author: ThreatConnect-Inc   File: validate.py    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(
                'Schema validation failed for {} ({}).'.format(layout_json_file, error)
            )
        else:
            self.check_layout_params() 
Example 13
Project: lear   Author: bcgov   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_schema_store(validate_schema: bool = False, schema_search_path: str = None) -> dict:
    """Return a schema_store as a dict.

    The default returns schema_store of the default schemas found in this package.
    """
    try:
        if not schema_search_path:
            schema_search_path = path.join(path.dirname(__file__), 'schemas')
        schemastore = {}
        fnames = listdir(schema_search_path)
        for fname in fnames:
            fpath = path.join(schema_search_path, fname)
            if fpath[-5:] == '.json':
                with open(fpath, 'r') as schema_fd:
                    schema = json.load(schema_fd)
                    if '$id' in schema:
                        schemastore[schema['$id']] = schema

        if validate_schema:
            for _, schema in schemastore.items():
                Draft7Validator.check_schema(schema)

        return schemastore
    except (SchemaError, json.JSONDecodeError) as error:
        # handle schema error
        raise error 
Example 14
Project: lear   Author: bcgov   File: utils.py    Apache License 2.0 5 votes vote down vote up
def validate(json_data: json,
             schema_id: str,
             schema_store: dict = None,
             validate_schema: bool = False,
             schema_search_path: str = None
             ) -> Tuple[bool, iter]:
    """Load the json file and validate against loaded schema."""
    try:
        if not schema_search_path:
            schema_search_path = path.join(path.dirname(__file__), 'schemas')

        if not schema_store:
            schema_store = get_schema_store(validate_schema, schema_search_path)

        schema = schema_store.get(f'{BASE_URI}/{schema_id}')
        if validate_schema:
            Draft7Validator.check_schema(schema)

        schema_file_path = path.join(schema_search_path, schema_id)
        resolver = RefResolver(f'file://{schema_file_path}.json', schema, schema_store)

        if Draft7Validator(schema,
                           format_checker=draft7_format_checker,
                           resolver=resolver
                           ) \
                .is_valid(json_data):
            return True, None

        errors = Draft7Validator(schema,
                                 format_checker=draft7_format_checker,
                                 resolver=resolver
                                 ) \
            .iter_errors(json_data)
        return False, errors

    except SchemaError as error:
        # handle schema error
        return False, error 
Example 15
Project: lear   Author: bcgov   File: test_validate_registry_schemas.py    Apache License 2.0 5 votes vote down vote up
def test_is_business_schema_valid(schema_filename):
    """Assert that the Schema is a valid Draft7 JSONSchema."""
    schema = get_schema(schema_filename)
    try:
        Draft7Validator.check_schema(schema)
        assert True
    except SchemaError as error:
        print(error)
        assert False 
Example 16
Project: lear   Author: bcgov   File: test_validate_registry_schemas.py    Apache License 2.0 5 votes vote down vote up
def test_get_schema_store():
    """Assert the schema store is setup correctly."""
    schema_store = get_schema_store()

    assert len(schema_store) == len(TEST_SCHEMAS_DATA)

    # assuming  test_is_business_schema_valid passes, this should pass too
    try:
        for k, schema in schema_store.items():
            print(f'checking schema:{k}')
            Draft7Validator.check_schema(schema)
    except SchemaError as error:
        print(error)
        assert False
    assert True 
Example 17
Project: jack   Author: uclnlp   File: validate.py    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 18
Project: acceptable   Author: canonical-ols   File: test_validation.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_raises_on_bad_schema(self):
        def fn():
            pass
        self.assertRaises(
            jsonschema.SchemaError,
            validate_body({'required': 'bar'}),
            fn
        ) 
Example 19
Project: acceptable   Author: canonical-ols   File: test_validation.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_raises_on_bad_schema(self):
        def fn():
            pass
        self.assertRaises(
            jsonschema.SchemaError,
            validate_output({'required': 'bar'}),
            fn
        ) 
Example 20
Project: acceptable   Author: canonical-ols   File: _validation.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def validate_schema(schema):
    """Validate that 'schema' is correct.

    This validates against the jsonschema v4 draft.

    :raises jsonschema.SchemaError: if the schema is invalid.
    """
    jsonschema.Draft4Validator.check_schema(schema) 
Example 21
Project: cjio   Author: cityjson   File: validation.py    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 22
Project: fedora-messaging   Author: fedora-infra   File: message.py    GNU General Public License v2.0 5 votes vote down vote up
def validate(self):
        """
        Validate the headers and body with the message schema, if any.

        In addition to the user-provided schema, all messages are checked against
        the base schema which requires certain message headers and the that body
        be a JSON object.

        .. warning:: This method should not be overridden by sub-classes.

        Raises:
            jsonschema.ValidationError: If either the message headers or the message body
                are invalid.
            jsonschema.SchemaError: If either the message header schema or the message body
                schema are invalid.
        """
        for schema in (self.headers_schema, Message.headers_schema):
            _log.debug(
                'Validating message headers "%r" with schema "%r"',
                self._headers,
                schema,
            )
            jsonschema.validate(self._headers, schema)
        for schema in (self.body_schema, Message.body_schema):
            _log.debug(
                'Validating message body "%r" with schema "%r"', self.body, schema
            )
            jsonschema.validate(self.body, schema) 
Example 23
Project: nmt-wizard-docker   Author: OpenNMT   File: test_config.py    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 24
Project: osparc-simcore   Author: ITISFoundation   File: jsonschema_validation.py    MIT License 5 votes vote down vote up
def validate_instance(instance: Dict, schema: Dict, *, log_errors=True):
    try:
        validate(instance, schema)
    except ValidationError:
        if log_errors:
            log.exception("Node validation error:")
        raise
    except SchemaError:
        if log_errors:
            log.exception("Schema validation error:")
        raise 
Example 25
Project: osparc-simcore   Author: ITISFoundation   File: test_template_projects.py    MIT License 5 votes vote down vote up
def project_specs(loop, project_schema_file: Path) -> Dict:
    # should not raise any exception
    try:
        specs = await create_jsonschema_specs(project_schema_file, session=None)
    except SchemaError:
        pytest.fail("validation of schema {} failed".format(project_schema_file))
    else:
        yield specs 
Example 26
Project: osparc-simcore   Author: ITISFoundation   File: validate-docker-image.py    MIT License 5 votes vote down vote up
def validate_docker_image(dockerimage: str, schema: Path):
    docker_labels = get_docker_image_labels(dockerimage)
    if docker_labels:
        log.info("Found docker labels in image %s", dockerimage)
        image_tags = {}
        for key in docker_labels.keys():
            if key.startswith("io.simcore."):
                try:
                    label_data = json.loads(docker_labels[key])
                except json.JSONDecodeError:
                    log.exception("Invalid json label %s", docker_labels[key])
                    raise
                for label_key in label_data.keys():
                    image_tags[label_key] = label_data[label_key]

        if image_tags:
            log.info("Found image tags in docker image")
            if not schema.exists():
                log.error("The file path to the schema is invalid!")
                return
            with schema.open() as fp:
                schema_specs = json.load(fp)
                log.info("Loaded schema specifications, validating...")
                try:
                    validate(image_tags, schema_specs)
                    log.info("%s is valid against %s! Congratulations!!", dockerimage, str(schema))
                except SchemaError:
                    log.exception("Invalid schema!")
                except ValidationError:
                    log.exception("Invalid image!") 
Example 27
Project: stash-scanner   Author: senuido   File: ItemFilter.py    GNU General Public License v3.0 5 votes vote down vote up
def init(cls):
        try:
            with open(Filter.FILTER_SCHEMA_FNAME) as f:
                schema = json.load(f)

            jsonschema.validate({}, schema)
        except jsonschema.ValidationError:
            cls.schema_validator = jsonschema.Draft4Validator(schema)
        except jsonschema.SchemaError as e:
            raise AppException('Failed loading filter validation schema.\n{}'.format(FILTER_SCHEMA_ERROR.format(e)))
        # except FileNotFoundError as e:
        except Exception as e:
            raise AppException('Failed loading filter validation schema.\n{}\n'
                               'Make sure the file are valid and in place.'.format(e)) 
Example 28
Project: binderhub   Author: jupyterhub   File: test_eventlog.py    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 29
Project: zoe   Author: DistributedSystemsGroup   File: applications.py    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 30
Project: trains-agent   Author: allegroai   File: request.py    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 31
Project: eq-survey-runner   Author: ONSdigital   File: test_feedback.py    MIT License 5 votes vote down vote up
def validate_json_with_schema(data, schema):
    errors = []

    try:
        validate(data, schema)

    except ValidationError as e:
        errors.append('Schema Validation Error! message [{}] does not validate against schema. Error [{}]'.format(data,
                                                                                                                  e))

    except SchemaError as e:
        errors.append('JSON Parse Error! Could not parse [{}]. Error [{}]'.format(data, e))

    return errors 
Example 32
Project: KNet   Author: knetsolutions   File: topology.py    Apache License 2.0 5 votes vote down vote up
def __validate(self, data):
        try:
            validate(data, schema)
        except jsonschema.ValidationError as e:
            log.error("json schema validation error %s", e.message)
            return False
        except jsonschema.SchemaError as e:
            log.error("json schema error %s", e.message)
            return False
        return True 
Example 33
Project: choppy-pipe   Author: go-choppy   File: utils.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self):
        from jsonschema import validate, ValidationError, SchemaError
        try:
            valid_result = validate(self.config, self.config_schema, None)
            if valid_result is None:
                self.logger.success("Cromwell config is valid.")
        except Exception as e:
            if isinstance(e, ValidationError):
                self.logger.error("Cromwell config is invalid: {}".format(e.message))
            elif isinstance(e, SchemaError):
                self.logger.error("Cromwell config schema is invalid: {}".format(e.message)) 
Example 34
Project: trains   Author: allegroai   File: request.py    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 35
Project: notifiers   Author: notifiers   File: core.py    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 36
Project: f5-cccl   Author: f5devcentral   File: validation.py    Apache License 2.0 5 votes vote down vote up
def __init__(self, schema=DEFAULT_LTM_SCHEMA):
        """Choose schema and initialize extended Draft4Validator.

        Raises:
            F5CcclSchemaError: Failed to read or validate the CCCL
            API schema file.
        """

        try:
            self.schema = read_yaml_or_json(schema)
        except json.JSONDecodeError as error:
            LOGGER.error("%s", error)
            raise cccl_exc.F5CcclSchemaError(
                'CCCL API schema could not be decoded.')
        except IOError as error:
            LOGGER.error("%s", error)
            raise cccl_exc.F5CcclSchemaError(
                'CCCL API schema could not be read.')

        try:
            Draft4Validator.check_schema(self.schema)
            self.validate_properties = Draft4Validator.VALIDATORS["properties"]
            validator_with_defaults = validators.extend(
                Draft4Validator,
                {"properties": self.__set_defaults})
            self.validator = validator_with_defaults(self.schema)
        except jsonschema.SchemaError as error:
            LOGGER.error("%s", error)
            raise cccl_exc.F5CcclSchemaError("Invalid API schema") 
Example 37
Project: CloudProcessingEngine-Decider   Author: bfansports   File: schema.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, input_spec):
        if input_spec:
            try:
                self._input_validator = jsonschema.Draft4Validator(input_spec)

            except jsonschema.SchemaError:
                raise

        else:
            self._input_validator = None 
Example 38
Project: jintolin   Author: yosshy   File: citype.py    Apache License 2.0 5 votes vote down vote up
def validate(self, data, **extra_attr):
        """
        Verifies schema
        """
        try:
            schema = copy(data)
            schema["$schema"] = "http://json-schema.org/schema#"
            jsonschema.Draft4Validator.check_schema(schema)
        except jsonschema.SchemaError as e:
            raise exc.ValidationError() 
Example 39
Project: ngta   Author: cavia-io   File: case.py    MIT License 5 votes vote down vote up
def check_json_by_schema(self, data, schema):
        msg = "response body with json schema should be successfully."
        try:
            logger.debug("response body with json schema: \n%s", pprint.pformat(schema))
            jsonschema.validate(data, schema)
        except (jsonschema.ValidationError, jsonschema.SchemaError):
            logger.exception("")
            self.fail_(msg)
        else:
            self.pass_(msg) 
Example 40
Project: swaggerit   Author: dutradda   File: method.py    MIT License 4 votes vote down vote up
def __call__(self, req, session):
        denied = await self._authorize(req, session)
        if denied is not None:
            return denied

        response_headers = {'content-type': 'application/json'}

        try:
            body_params = await self._build_body_params(req)
            query_params = self._build_non_body_params(self._query_validator, req.query)
            path_params = self._build_non_body_params(self._path_validator,
                                                               req.path_params)
            headers_params = self._build_non_body_params(self._headers_validator, dict(req.headers))

        except (ValidationError, SchemaError) as error:
            return self._valdation_error_to_response(error, response_headers)

        req = SwaggerRequest(
            req.path,
            req.method,
            scheme=req.scheme,
            host=req.host,
            path_params=path_params,
            query=query_params,
            headers=headers_params,
            body=body_params,
            body_schema=self._body_validator.schema if self._body_validator else None,
            context=req.context
        )

        try:
            if session is None:
                resp = await self._operation(req)
            else:
                resp = await self._operation(req, session)

        except (ValidationError, SchemaError) as error:
            return self._valdation_error_to_response(error, response_headers)

        except Exception as error:
            body = ujson.dumps({'message': 'Something unexpected happened'})
            self._logger.exception('Unexpected')
            return SwaggerResponse(500, body=body, headers=response_headers)

        else:
            if resp.headers.get('content-type') is None:
                resp.headers.update(response_headers)
            return resp 
Example 41
Project: YODA-File   Author: ODM2   File: display_file.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def df_validate(args ):

    level = args.level

    validation_log =["validation starting"]
    stream = file(args.source)

    ymal_data = yaml.load (stream)

    validation_log.append("level 0: File valid JSON or YAML")
    if (level > 0 ):
        schema = file(args.schema)
        json_schema = json.load(schema)
        validation_log.append("Starting Level 2")
        try:
            v = Draft4Validator(json_schema)
            errors = v.iter_errors(ymal_data)
            # building an ErrorTree fails.
            # Means we can't use ErrorTree to get a count or provide more details.
            #   possibly to do  Space in KeyName?.
            #tree = ErrorTree(errors)
            #tree = ErrorTree(v.iter_errors(ymal_data))
            errorList =  list(sorted(errors, key=lambda e: e.path))

           #if (tree.total_errors==0 ) :
            if (len(errorList) == 0):
                logger.info('Level 2 validation; File valid to Display File Structural Specification')
                return

            #for error in tree.errors:
            for error in errorList:
                logger.info ('in iterated errors')
                logger.warn (  error.message + ' in ' +
                "/".join( [ str(element) for element in error.path ] )
                )
        except ValidationError as e:
            logger.info ('in validation error')
            logger.warn(e.message)
        except SchemaError as e:
            logger.error(e)


    pass 
Example 42
Project: armada   Author: airshipit   File: validate.py    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 43
Project: stash-scanner   Author: senuido   File: FilterManager.py    GNU General Public License v3.0 4 votes vote down vote up
def loadFiltersFromFile(cls, fname, validate_data):
        filters = []

        cur_fname = fname
        try:
            with cls.filter_file_lock[fname]:
                with open(cur_fname, encoding="utf-8", errors="replace") as f:
                    data = json.load(f)

            cur_fname = FILTERS_FILE_SCHEMA_FNAME  # TODO: move schema loading to main init and store in class
            with open(cur_fname) as f:
                schema = json.load(f)

            # normalize keys and values
            data = lower_json(data)

            jsonschema.validate(data, schema)

            for item in data.get('filters', []):
                fltr = Filter.fromDict(item)
                filters.append(fltr)

            ver = data.get('version', FilterVersion.V1)
            if ver != FilterVersion.Latest:
                FilterManager.convert(ver, filters)
            last_update = data.get('last_update', '')

            if validate_data:
                for fltr in filters:
                    fltr.validate()

            try:
                last_update = datetime.strptime(last_update, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                last_update = datetime.utcnow() - timedelta(minutes=FilterManager.UPDATE_INTERVAL)
        except FileNotFoundError:
            if cur_fname != FILTERS_FILE_SCHEMA_FNAME:
                raise
            else:
                raise AppException(FILTER_FILE_MISSING.format(cur_fname))
        except jsonschema.ValidationError as e:
            raise AppException(FILTERS_FILE_VALIDATION_ERROR.format(get_verror_msg(e, data)))
        except jsonschema.SchemaError as e:
            raise AppException(FILTERS_FILE_SCHEMA_ERROR.format(e.message))
        except json.decoder.JSONDecodeError as e:
            raise AppException(FILTER_INVALID_JSON.format(e, cur_fname))

        return filters, last_update 
Example 44
Project: easyucs   Author: vesposito   File: manager.py    GNU General Public License v2.0 4 votes vote down vote up
def _validate_config_from_json(self, config_json=None):
        """
        Validates a config using the JSON schema definition
        :param config_json: JSON content containing config to be validated
        :return: True if config is valid, False otherwise
        """

        # Open JSON master schema for a UCS System config
        json_file = open("schema/ucs/ucsm/master.json")
        json_string = json_file.read()
        json_file.close()
        json_schema = json.loads(json_string)

        schema_path = 'file:///{0}/'.format(
            os.path.dirname(os.path.abspath("schema/ucs/ucsm/master.json")).replace("\\", "/"))
        resolver = jsonschema.RefResolver(schema_path, json_schema)
        format_checker = jsonschema.FormatChecker()

        try:
            jsonschema.validate(config_json, json_schema, resolver=resolver, format_checker=format_checker)
        except jsonschema.ValidationError as err:
            absolute_path = []
            for path in err.absolute_path:
                absolute_path.append(path)

            # TODO: Improve error logging by providing a simple explanation when JSON file is not valid
            self.logger(level="error", message="Invalid config JSON file in " + str(absolute_path))
            self.logger(level="error", message="Failed to validate config JSON file using schema: " + str(err.message))
            return False
        except jsonschema.SchemaError as err:
            self.logger(level="error", message="Failed to validate config JSON file due to schema error: " + str(err))
            return False

        # We now validate that the easyucs_version of the file is not greater than the running version of EasyUCS
        easyucs_version_from_file = config_json["easyucs"]["metadata"][0]["easyucs_version"]
        if packaging_version.parse(easyucs_version_from_file) > packaging_version.parse(__version__):
            self.logger(level="error",
                        message="Failed to validate config JSON file because it has been created using a more " +
                                "recent version of EasyUCS (" + easyucs_version_from_file + " > " + __version__ + ")")
            return False

        return True 
Example 45
Project: easyucs   Author: vesposito   File: manager.py    GNU General Public License v2.0 4 votes vote down vote up
def _validate_config_from_json(self, config_json=None):
        """
        Validates a config using the JSON schema definition
        :param config_json: JSON content containing config to be validated
        :return: True if config is valid, False otherwise
        """

        # Open JSON master schema for a UCS CIMC config
        json_file = open("schema/ucs/cimc/master.json")
        json_string = json_file.read()
        json_file.close()
        json_schema = json.loads(json_string)

        schema_path = 'file:///{0}/'.format(
            os.path.dirname(os.path.abspath("schema/ucs/cimc/master.json")).replace("\\", "/"))
        resolver = jsonschema.RefResolver(schema_path, json_schema)
        format_checker = jsonschema.FormatChecker()

        try:
            jsonschema.validate(config_json, json_schema, resolver=resolver, format_checker=format_checker)
        except jsonschema.ValidationError as err:
            absolute_path = []
            while True:
                try:
                    value = err.absolute_path.popleft()
                    if value != 0:
                        absolute_path.append(value)
                except IndexError:
                    break
            # TODO: Improve error logging by providing a simple explanation when JSON file is not valid
            self.logger(level="error", message="Invalid config JSON file in " + str(absolute_path))
            self.logger(level="error", message="Failed to validate config JSON file using schema: " + str(err.message))
            return False
        except jsonschema.SchemaError as err:
            self.logger(level="error", message="Failed to validate config JSON file due to schema error: " + str(err))
            return False

        # We now validate that the easyucs_version of the file is not greater than the running version of EasyUCS
        easyucs_version_from_file = config_json["easyucs"]["metadata"][0]["easyucs_version"]
        if packaging_version.parse(easyucs_version_from_file) > packaging_version.parse(__version__):
            self.logger(level="error",
                        message="Failed to validate config JSON file because it has been created using a more " +
                                "recent version of EasyUCS (" + easyucs_version_from_file + " > " + __version__ + ")")
            return False

        return True 
Example 46
Project: easyucs   Author: vesposito   File: manager.py    GNU General Public License v2.0 4 votes vote down vote up
def _validate_config_from_json(self, config_json=None):
        """
        Validates a config using the JSON schema definition
        :param config_json: JSON content containing config to be validated
        :return: True if config is valid, False otherwise
        """

        # Open JSON master schema for a UCS Central config
        json_file = open("schema/ucs/ucsc/master.json")
        json_string = json_file.read()
        json_file.close()
        json_schema = json.loads(json_string)

        schema_path = 'file:///{0}/'.format(
            os.path.dirname(os.path.abspath("schema/ucs/ucsc/master.json")).replace("\\", "/"))
        resolver = jsonschema.RefResolver(schema_path, json_schema)
        format_checker = jsonschema.FormatChecker()

        try:
            jsonschema.validate(config_json, json_schema, resolver=resolver, format_checker=format_checker)
        except jsonschema.ValidationError as err:
            absolute_path = []
            while True:
                try:
                    value = err.absolute_path.popleft()
                    if value != 0:
                        absolute_path.append(value)
                except IndexError:
                    break
            # TODO: Improve error logging by providing a simple explanation when JSON file is not valid
            self.logger(level="error", message="Invalid config JSON file in " + str(absolute_path))
            self.logger(level="error", message="Failed to validate config JSON file using schema: " + str(err.message))
            return False
        except jsonschema.SchemaError as err:
            self.logger(level="error", message="Failed to validate config JSON file due to schema error: " + str(err))
            return False

        # We now validate that the easyucs_version of the file is not greater than the running version of EasyUCS
        easyucs_version_from_file = config_json["easyucs"]["metadata"][0]["easyucs_version"]
        if packaging_version.parse(easyucs_version_from_file) > packaging_version.parse(__version__):
            self.logger(level="error",
                        message="Failed to validate config JSON file because it has been created using a more " +
                                "recent version of EasyUCS (" + easyucs_version_from_file + " > " + __version__ + ")")
            return False

        return True