Python jsonschema.Draft4Validator() Examples

The following are 30 code examples of jsonschema.Draft4Validator(). 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: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 7 votes vote down vote up
def test_oneOf_and_anyOf_are_weak_matches(self):
        """
        A property you *must* match is probably better than one you have to
        match a part of.

        """

        validator = Draft4Validator(
            {
                "minProperties": 2,
                "anyOf": [{"type": "string"}, {"type": "number"}],
                "oneOf": [{"type": "string"}, {"type": "number"}],
            }
        )
        best = self.best_match(validator.iter_errors({}))
        self.assertEqual(best.validator, "minProperties") 
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: 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 #4
Source File: test_exceptions.py    From core with MIT License 6 votes vote down vote up
def test_nested_context_for_oneOf(self):
        validator = Draft4Validator(
            {
                "properties" : {
                    "foo" : {
                        "oneOf" : [
                            {"type" : "string"},
                            {
                                "oneOf" : [
                                    {"type" : "string"},
                                    {
                                        "properties" : {
                                            "bar" : {"type" : "array"}
                                        },
                                    },
                                ],
                            },
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo" : {"bar" : 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #5
Source File: validator.py    From os-net-config with Apache License 2.0 6 votes vote down vote up
def _validate_config(config, config_name, schema, filter_errors):
    error_messages = []
    validator = jsonschema.Draft4Validator(schema)
    v_errors = validator.iter_errors(config)
    v_errors = sorted(v_errors, key=lambda e: e.path)
    for v_error in v_errors:
        error_message = _get_consistent_error_message(v_error)
        details = _get_detailed_errors(v_error, 1, v_error.schema_path,
                                       schema, filter_errors=filter_errors)

        config_path = '/'.join([str(x) for x in v_error.path])
        if details:
            error_messages.append(
                "{} failed schema validation at network_config/{}:\n"
                "    {}\n"
                "  Sub-schemas tested and not matching:\n"
                "  {}"
                .format(config_name, config_path, error_message,
                        '\n  '.join(details)))
        else:
            error_messages.append(
                "{} failed schema validation at network_config/{}:\n"
                "    {}"
                .format(config_name, config_path, error_message))
    return error_messages 
Example #6
Source File: test_exceptions.py    From core with MIT License 6 votes vote down vote up
def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
        """
        If the most relevant error is an oneOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties" : {
                    "foo" : {
                        "oneOf" : [
                            {"type" : "string"},
                            {"properties" : {"bar" : {"type" : "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo" : {"bar" : 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #7
Source File: test_exceptions.py    From core with MIT License 6 votes vote down vote up
def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
        """
        If the most relevant error is an anyOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties" : {
                    "foo" : {
                        "anyOf" : [
                            {"type" : "string"},
                            {"properties" : {"bar" : {"type" : "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo" : {"bar" : 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #8
Source File: test_exceptions.py    From core with MIT License 6 votes vote down vote up
def test_oneOf_and_anyOf_are_weak_matches(self):
        """
        A property you *must* match is probably better than one you have to
        match a part of.

        """

        validator = Draft4Validator(
            {
                "minProperties" : 2,
                "anyOf" : [{"type" : "string"}, {"type" : "number"}],
                "oneOf" : [{"type" : "string"}, {"type" : "number"}],
            }
        )
        best = self.best_match(validator.iter_errors({}))
        self.assertEqual(best.validator, "minProperties") 
Example #9
Source File: deckhand.py    From drydock with Apache License 2.0 6 votes vote down vote up
def validate_drydock_document(self, doc):
        """Validate a parsed document via jsonschema.

        If a schema for a document Kind is not available, the document is
        considered valid. Schema is chosen by the doc['kind'] field.

        Returns a empty list for valid documents, otherwise returns a list
        of all found errors

        :param doc: dictionary of the parsed document.
        """
        schemaname = doc.get('schema', '')
        (schema_ns, doc_kind, doc_version) = schemaname.split('/')

        errors_found = []

        if doc_version == 'v1':
            if schemaname in self.v1_doc_schemas:
                validator = jsonschema.Draft4Validator(
                    self.v1_doc_schemas.get(schemaname))
                for error in validator.iter_errors(doc.get('data', [])):
                    errors_found.append(error.message)

        return errors_found 
Example #10
Source File: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_nested_context_for_oneOf(self):
        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "oneOf": [
                            {"type": "string"},
                            {
                                "oneOf": [
                                    {"type": "string"},
                                    {
                                        "properties": {
                                            "bar": {"type": "array"},
                                        },
                                    },
                                ],
                            },
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #11
Source File: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):
        """
        Now, if the error is allOf, we traverse but select the *most* relevant
        error from the context, because all schemas here must match anyways.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "allOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "string") 
Example #12
Source File: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_oneOf_and_anyOf_are_weak_matches(self):
        """
        A property you *must* match is probably better than one you have to
        match a part of.

        """

        validator = Draft4Validator(
            {
                "minProperties": 2,
                "anyOf": [{"type": "string"}, {"type": "number"}],
                "oneOf": [{"type": "string"}, {"type": "number"}],
            }
        )
        best = self.best_match(validator.iter_errors({}))
        self.assertEqual(best.validator, "minProperties") 
Example #13
Source File: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
        """
        If the most relevant error is an anyOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "anyOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #14
Source File: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
        """
        If the most relevant error is an anyOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "anyOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #15
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 #16
Source File: check_tap.py    From singer-tools with Apache License 2.0 6 votes vote down vote up
def add(self, message):
        if isinstance(message, singer.RecordMessage):
            stream = self.ensure_stream(message.stream)
            if stream.latest_schema:
                validator_fn = extend_with_default(Draft4Validator)
                validator = validator_fn(
                    stream.latest_schema, format_checker=FormatChecker())
                validator.validate(copy.deepcopy(message.record))
            else:
                print('I saw a record for stream {} before the schema'.format(
                    message.stream))
                exit(1)
            stream.num_records += 1

        elif isinstance(message, singer.SchemaMessage):
            stream = self.ensure_stream(message.stream)
            stream.num_schemas += 1
            stream.latest_schema = message.schema

        elif isinstance(message, singer.StateMessage):
            self.latest_state = message.value
            self.num_states += 1 
Example #17
Source File: test_exceptions.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
        """
        If the most relevant error is an oneOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "oneOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #18
Source File: kafka_monitor.py    From scrapy-cluster with MIT License 6 votes vote down vote up
def setup(self, level=None, log_file=None, json=None):
        '''
        Load everything up. Note that any arg here will override both
        default and custom settings

        @param level: the log level
        @param log_file: boolean t/f whether to log to a file, else stdout
        @param json: boolean t/f whether to write the logs in json
        '''
        self.settings = self.wrapper.load(self.settings_name)

        my_level = level if level else self.settings['LOG_LEVEL']
        # negate because logger wants True for std out
        my_output = not log_file if log_file else self.settings['LOG_STDOUT']
        my_json = json if json else self.settings['LOG_JSON']
        self.logger = LogFactory.get_instance(json=my_json, stdout=my_output,
                                              level=my_level,
                                              name=self.settings['LOGGER_NAME'],
                                              dir=self.settings['LOG_DIR'],
                                              file=self.settings['LOG_FILE'],
                                              bytes=self.settings['LOG_MAX_BYTES'],
                                              backups=self.settings['LOG_BACKUPS'])

        self.validator = self.extend_with_default(Draft4Validator) 
Example #19
Source File: yaml.py    From drydock with Apache License 2.0 6 votes vote down vote up
def validate_drydock_document(self, doc):
        """Validate a parsed document via jsonschema.

        If a schema for a document Kind is not available, the document is
        considered valid. Schema is chosen by the doc['kind'] field.

        Returns a empty list for valid documents, otherwise returns a list
        of all found errors

        :param doc: dictionary of the parsed document.
        """
        doc_kind = doc.get('kind')
        if doc_kind in self.v1_doc_schemas:
            validator = jsonschema.Draft4Validator(
                self.v1_doc_schemas.get(doc_kind))
            errors_found = []
            for error in validator.iter_errors(doc):
                errors_found.append(error.message)
            return errors_found
        else:
            return [] 
Example #20
Source File: test_validator.py    From os-net-config with Apache License 2.0 6 votes vote down vote up
def test_bool_or_param(self):
        schema = validator.get_schema_for_defined_type("bool_or_param")
        v = jsonschema.Draft4Validator(schema)
        self.assertTrue(v.is_valid(True))
        self.assertTrue(v.is_valid(False))
        self.assertTrue(v.is_valid("TRUE"))
        self.assertTrue(v.is_valid("true"))
        self.assertTrue(v.is_valid("yes"))
        self.assertTrue(v.is_valid("1"))
        self.assertTrue(v.is_valid("on"))
        self.assertTrue(v.is_valid("false"))
        self.assertTrue(v.is_valid("FALSE"))
        self.assertTrue(v.is_valid("off"))
        self.assertTrue(v.is_valid("no"))
        self.assertTrue(v.is_valid("0"))
        self.assertFalse(v.is_valid([]))
        self.assertFalse(v.is_valid({}))
        self.assertFalse(v.is_valid(None))
        self.assertFalse(v.is_valid("falsch")) 
Example #21
Source File: test_validator.py    From os-net-config with Apache License 2.0 6 votes vote down vote up
def test_interface(self):
        schema = validator.get_schema_for_defined_type("interface")
        v = jsonschema.Draft4Validator(schema)
        data = {
            "type": "interface",
            "name": "em1",
            "use_dhcp": False,
            "addresses": [{
                "ip_netmask": "192.0.2.1/24"
            }],
            "defroute": False,
            "dhclient_args": "--foobar",
            "dns_servers": ["1.2.3.4"],
            "domain": "openstack.local",
            "mtu": 1501,
            "ethtool_opts": "speed 1000 duplex full",
            "hotplug": True,
            "onboot": True,
            "routes": [{
                "next_hop": "192.0.2.1",
                "ip_netmask": "192.0.2.1/24",
                "route_options": "metric 10"
            }]
        }
        self.assertTrue(v.is_valid(data)) 
Example #22
Source File: test_validator.py    From os-net-config with Apache License 2.0 6 votes vote down vote up
def test_ovs_bridge(self):
        schema = validator.get_schema_for_defined_type("ovs_bridge")
        v = jsonschema.Draft4Validator(schema)
        data = {
            "type": "ovs_bridge",
            "name": "br-ctlplane",
            "ovs_options": "lacp=active",
            "ovs_extra": [
                "br-set-external-id br-ctlplane bridge-id br-ctlplane",
                "set bridge {name} stp_enable=true"
            ],
            "ovs_fail_mode": "secure",
            "members": [
                {"type": "interface", "name": "em1"}
            ]
        }
        self.assertTrue(v.is_valid(data)) 
Example #23
Source File: test_validator.py    From os-net-config with Apache License 2.0 6 votes vote down vote up
def test_nfvswitch_bridge(self):
        schema = validator.get_schema_for_defined_type("nfvswitch_bridge")
        v = jsonschema.Draft4Validator(schema)
        data = {
            "type": "nfvswitch_bridge",
            "options": "-c 2,3,4,5",
            "members": [{
                "type": "nfvswitch_internal",
                "name": "api",
                "addresses": [
                    {"ip_netmask": "172.16.2.7/24"}
                ],
                "vlan_id": 201
            }, {
                "type": "nfvswitch_internal",
                "name": "storage",
                "addresses": [
                    {"ip_netmask": "172.16.1.6/24"}
                ],
                "vlan_id": 202
            }]
        }
        self.assertTrue(v.is_valid(data)) 
Example #24
Source File: validator.py    From python-sdk with Apache License 2.0 6 votes vote down vote up
def is_datafile_valid(datafile):
    """ Given a datafile determine if it is valid or not.

  Args:
    datafile: JSON string representing the project.

  Returns:
    Boolean depending upon whether datafile is valid or not.
  """

    try:
        datafile_json = json.loads(datafile)
    except:
        return False

    try:
        jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
    except:
        return False

    return True 
Example #25
Source File: test_exceptions.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self):
        """
        If the most relevant error is an anyOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "anyOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #26
Source File: test_exceptions.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self):
        """
        If the most relevant error is an oneOf, then we traverse its context
        and select the otherwise *least* relevant error, since in this case
        that means the most specific, deep, error inside the instance.

        I.e. since only one of the schemas must match, we look for the most
        relevant one.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "oneOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #27
Source File: test_exceptions.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self):
        """
        Now, if the error is allOf, we traverse but select the *most* relevant
        error from the context, because all schemas here must match anyways.

        """

        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "allOf": [
                            {"type": "string"},
                            {"properties": {"bar": {"type": "array"}}},
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "string") 
Example #28
Source File: test_exceptions.py    From deepWordBug with Apache License 2.0 6 votes vote down vote up
def test_nested_context_for_oneOf(self):
        validator = Draft4Validator(
            {
                "properties": {
                    "foo": {
                        "oneOf": [
                            {"type": "string"},
                            {
                                "oneOf": [
                                    {"type": "string"},
                                    {
                                        "properties": {
                                            "bar": {"type": "array"},
                                        },
                                    },
                                ],
                            },
                        ],
                    },
                },
            },
        )
        best = self.best_match(validator.iter_errors({"foo": {"bar": 12}}))
        self.assertEqual(best.validator_value, "array") 
Example #29
Source File: cluster.py    From flocker with Apache License 2.0 6 votes vote down vote up
def validate_host_mapping(host_mapping):
    """
    Validate a provided host mapping.

    :param dict host_mapping: The parsed JSON host mapping from the
    environment variable ``FLOCKER_ACCEPTANCE_HOSTNAME_TO_PUBLIC_ADDRESS``.
    :raises: jsonschema.ValidationError if the configuration is invalid.
    """
    schema = {
        "$schema": "http://json-schema.org/draft-04/schema#",
        "type": "object",
        "additionalProperties": "true",
    }

    v = Draft4Validator(schema, format_checker=FormatChecker())
    v.validate(host_mapping) 
Example #30
Source File: validate_importers.py    From cornerwise with MIT License 6 votes vote down vote up
def handle(self, *args, **options):
        err = lambda m: self.stderr.write(self.style.ERROR(m) + "\n")
        succ = lambda m: self.stdout.write(self.style.SUCCESS(m) + "\n")
        when = datetime.now() - timedelta(days=30)
        validator = Draft4Validator(get_importer_schema())

        for importer in Importer.objects.all():
            errors = defaultdict(list)
            for error in validator.iter_errors(importer.updated_since(when)):
                errors[schema_path_str(error.absolute_schema_path)].append(error)

            if errors:
                err(f"{len(errors)} error(s) in {importer}:")
                for path, errs in errors.items():
                    error = errs[0]
                    repeats = f" ({len(errs)} repeats)" if len(errs) > 1 else ""
                    err(f"at {path}{repeats}:\n{error.message}\n")
            else:
                succ(f"{importer} validated successfully!")