Python jsonschema.exceptions.SchemaError() Examples

The following are 12 code examples of jsonschema.exceptions.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.exceptions , or try the search function .
Example #1
Source File: serializers.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def validate_json(self, data):
        try:
            validator = jsonschema.Draft4Validator(self.schema)
            validation_errors = [e for e in validator.iter_errors(data)]

            # Iteratre over all errors and raise as single exception
            if validation_errors:
                exception_msgs = {}
                for err in validation_errors:
                    if err.path:
                        field = '-'.join([str(e) for e in err.path])
                    elif err.schema_path:
                        field = '-'.join([str(e) for e in err.schema_path])
                    else:
                        field = 'error'

                    if field in exception_msgs:
                        exception_msgs[field].append(err.message)
                    else:          
                        exception_msgs[field] = [err.message]  
                raise serializers.ValidationError(exception_msgs)

        except (JSONSchemaValidationError, JSONSchemaError) as e:
            raise serializers.ValidationError(e.message)
        return self.to_internal_value(json.dumps(data)) 
Example #2
Source File: test_cli.py    From deepWordBug with Apache License 2.0 7 votes vote down vote up
def test_draft3_schema_draft4_validator(self):
        stdout, stderr = StringIO(), StringIO()
        with self.assertRaises(SchemaError):
            cli.run(
                {
                    "validator": Draft4Validator,
                    "schema": {
                        "anyOf": [
                            {"minimum": 20},
                            {"type": "string"},
                            {"required": True},
                        ],
                    },
                    "instances": [1],
                    "error_format": "{error.message}",
                },
                stdout=stdout,
                stderr=stderr,
            ) 
Example #3
Source File: test_cli.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_draft3_schema_draft4_validator(self):
        stdout, stderr = StringIO(), StringIO()
        with self.assertRaises(SchemaError):
            cli.run(
                {
                    "validator": Draft4Validator,
                    "schema": {
                        "anyOf": [
                            {"minimum": 20},
                            {"type": "string"},
                            {"required": True},
                        ],
                    },
                    "instances": [1],
                    "error_format": "{error.message}",
                },
                stdout=stdout,
                stderr=stderr,
            ) 
Example #4
Source File: test_cli.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_draft3_schema_draft4_validator(self):
        stdout, stderr = StringIO(), StringIO()
        with self.assertRaises(SchemaError):
            cli.run(
                {
                    "validator": Draft4Validator,
                    "schema": {
                        "anyOf": [
                            {"minimum": 20},
                            {"type": "string"},
                            {"required": True},
                        ],
                    },
                    "instances": [1],
                    "error_format": "{error.message}",
                },
                stdout=stdout,
                stderr=stderr,
            ) 
Example #5
Source File: test_cli.py    From accelerated-data-lake with Apache License 2.0 6 votes vote down vote up
def test_draft3_schema_draft4_validator(self):
        stdout, stderr = StringIO(), StringIO()
        with self.assertRaises(SchemaError):
            cli.run(
                {
                    "validator": Draft4Validator,
                    "schema": {
                        "anyOf": [
                            {"minimum": 20},
                            {"type": "string"},
                            {"required": True},
                        ],
                    },
                    "instances": [1],
                    "error_format": "{error.message}",
                },
                stdout=stdout,
                stderr=stderr,
            ) 
Example #6
Source File: test_cli.py    From Requester with MIT License 6 votes vote down vote up
def test_draft3_schema_draft4_validator(self):
        stdout, stderr = StringIO(), StringIO()
        with self.assertRaises(SchemaError):
            cli.run(
                {
                    "validator": Draft4Validator,
                    "schema": {
                        "anyOf": [
                            {"minimum": 20},
                            {"type": "string"},
                            {"required": True},
                        ],
                    },
                    "instances": [1],
                    "error_format": "{error.message}",
                },
                stdout=stdout,
                stderr=stderr,
            ) 
Example #7
Source File: json_schemas.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def validate_json(json_string, schema):
    """
    invokes the validate function of jsonschema
    """
    schema_dict = json.loads(schema)
    schema_title = schema_dict['title']
    try:
        validate(json_string, schema_dict)
    except ValidationError as err:
        title = 'JSON validation failed: {}'.format(err.message)
        description = 'Failed validator: {} : {}'.format(
            err.validator,
            err.validator_value
        )
        LOG.error(title)
        LOG.error(description)
        raise InvalidFormatError(
            title=title,
            description=description,
        )
    except SchemaError as err:
        title = 'SchemaError: Unable to validate JSON: {}'.format(err)
        description = 'Invalid Schema: {}'.format(schema_title)
        LOG.error(title)
        LOG.error(description)
        raise AppError(
            title=title,
            description=description
        )
    except FormatError as err:
        title = 'FormatError: Unable to validate JSON: {}'.format(err)
        description = 'Invalid Format: {}'.format(schema_title)
        LOG.error(title)
        LOG.error(description)
        raise AppError(
            title=title,
            description=description
        )


# The action resource structure 
Example #8
Source File: keywords.py    From RESTinstance with Apache License 2.0 5 votes vote down vote up
def _assert_schema(self, schema, reality):
        try:
            validate(reality, schema, format_checker=FormatChecker())
        except SchemaError as e:
            raise RuntimeError(e)
        except ValidationError as e:
            raise AssertionError(e) 
Example #9
Source File: test_response_validator.py    From behave-restful with MIT License 5 votes vote down vote up
def test_raises_if_schema_is_invalid(self):
        with self.assertRaises(jse.SchemaError):
            self.schema = """
            {
                "not": "valid schema",
                "but": "Valid json"
            }
            """
            self.given_json({
                'id': 1
            }).validate()


    # response_json_matches_defined_schema() 
Example #10
Source File: test_item.py    From scrapy-jsonschema with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_schema(self):
        with pytest.raises(SchemaError):

            class TestItem1(JsonSchemaItem):
                jsonschema = invalid_schema 
Example #11
Source File: test_item_schema.py    From scrapy-jsonschema with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_schema(self):
        try:

            class TestItem1(JsonSchemaItem):
                jsonschema = invalid_schema

        except SchemaError:
            pass
        else:
            self.fail('SchemaError was not raised') 
Example #12
Source File: json_schema.py    From target-postgres with GNU Affero General Public License v3.0 5 votes vote down vote up
def validation_errors(schema):
    """
    Given a dict, returns any known JSON Schema validation errors. If there are none,
    implies that the dict is a valid JSON Schema.
    :param schema: dict
    :return: [String, ...]
    """

    errors = []

    if not isinstance(schema, dict):
        errors.append('Parameter `schema` is not a dict, instead found: {}'.format(type(schema)))

    try:
        if not _valid_schema_version(schema):
            errors.append('Schema version must be Draft 4. Found: {}'.format('$schema'))
    except Exception as ex:
        errors = _unexpected_validation_error(errors, ex)

    try:
        Draft4Validator.check_schema(schema)
    except SchemaError as error:
        errors.append(str(error))
    except Exception as ex:
        errors = _unexpected_validation_error(errors, ex)

    try:
        simplify(schema)
    except JSONSchemaError as error:
        errors.append(str(error))
    except Exception as ex:
        errors = _unexpected_validation_error(errors, ex)

    return errors