Python jsonschema.ValidationError() Examples
The following are 30
code examples of jsonschema.ValidationError().
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: config.py From query-exporter with GNU General Public License v3.0 | 8 votes |
def _validate_config(config: Dict[str, Any]): schema_path = PACKAGE.get_resource_filename( # type: ignore None, "query_exporter/schemas/config.yaml" ) with open(schema_path) as fd: schema = yaml.safe_load(fd) try: jsonschema.validate(config, schema) except jsonschema.ValidationError as e: path = "/".join(str(item) for item in e.absolute_path) raise ConfigError(f"Invalid config at {path}: {e.message}")
Example #2
Source File: validators.py From zun with Apache License 2.0 | 8 votes |
def validate(self, *args, **kwargs): try: self.validator.validate(*args, **kwargs) except jsonschema.ValidationError as ex: if len(ex.path) > 0: if self.is_body: detail = _("Invalid input for field '%(path)s'." "Value: '%(value)s'. %(message)s") else: detail = _("Invalid input for query parameters " "'%(path)s'. Value: '%(value)s'. %(message)s") detail = detail % { 'path': ex.path.pop(), 'value': ex.instance, 'message': str(ex) } else: detail = ex.message raise exception.SchemaValidationError(detail=detail)
Example #3
Source File: test_cli.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def test_unsuccessful_validation(self): error = ValidationError("I am an error!", instance=1) stdout, stderr = StringIO(), StringIO() exit_code = cli.run( { "validator": fake_validator([error]), "schema": {}, "instances": [1], "error_format": "{error.instance} - {error.message}", }, stdout=stdout, stderr=stderr, ) self.assertFalse(stdout.getvalue()) self.assertEqual(stderr.getvalue(), "1 - I am an error!") self.assertEqual(exit_code, 1)
Example #4
Source File: _validators.py From designate with Apache License 2.0 | 6 votes |
def oneOf_draft3(validator, oneOf, instance, schema): # Backported from Draft4 to Draft3 subschemas = iter(oneOf) first_valid = next( (s for s in subschemas if validator.is_valid(instance, s)), None, ) if first_valid is None: yield jsonschema.ValidationError( "%r is not valid under any of the given schemas." % (instance,) ) else: more_valid = [s for s in subschemas if validator.is_valid(instance, s)] if more_valid: more_valid.append(first_valid) reprs = ", ".join(repr(schema) for schema in more_valid) yield jsonschema.ValidationError( "%r is valid under each of %s" % (instance, reprs) )
Example #5
Source File: test_cli.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def test_unsuccessful_validation(self): error = ValidationError("I am an error!", instance=1) stdout, stderr = StringIO(), StringIO() exit_code = cli.run( { "validator": fake_validator([error]), "schema": {}, "instances": [1], "error_format": "{error.instance} - {error.message}", }, stdout=stdout, stderr=stderr, ) self.assertFalse(stdout.getvalue()) self.assertEqual(stderr.getvalue(), "1 - I am an error!") self.assertEqual(exit_code, 1)
Example #6
Source File: _validators.py From designate with Apache License 2.0 | 6 votes |
def type_draft3(validator, types, instance, schema): types = _utils.ensure_list(types) # NOTE(kiall): A datetime object is not a string, but is still valid. if ('format' in schema and schema['format'] == 'date-time' and isinstance(instance, datetime.datetime)): return all_errors = [] for index, type in enumerate(types): if type == "any": return if validator.is_type(type, "object"): errors = list(validator.descend(instance, type, schema_path=index)) if not errors: return all_errors.extend(errors) else: if validator.is_type(instance, type): return else: yield jsonschema.ValidationError( _utils.types_msg(instance, types), context=all_errors, )
Example #7
Source File: test_cli.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def test_unsuccessful_validation_multiple_instances(self): first_errors = [ ValidationError("9", instance=1), ValidationError("8", instance=1), ] second_errors = [ValidationError("7", instance=2)] stdout, stderr = StringIO(), StringIO() exit_code = cli.run( { "validator": fake_validator(first_errors, second_errors), "schema": {}, "instances": [1, 2], "error_format": "{error.instance} - {error.message}\t", }, stdout=stdout, stderr=stderr, ) self.assertFalse(stdout.getvalue()) self.assertEqual(stderr.getvalue(), "1 - 9\t1 - 8\t2 - 7\t") self.assertEqual(exit_code, 1)
Example #8
Source File: test_validators.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def test_it_delegates_to_a_legacy_ref_resolver(self): """ Legacy RefResolvers support only the context manager form of resolution. """ class LegacyRefResolver(object): @contextmanager def resolving(this, ref): self.assertEqual(ref, "the ref") yield {"type": "integer"} resolver = LegacyRefResolver() schema = {"$ref": "the ref"} with self.assertRaises(ValidationError): self.validator_class(schema, resolver=resolver).validate(None)
Example #9
Source File: test_validators.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def test_it_delegates_to_a_legacy_ref_resolver(self): """ Legacy RefResolvers support only the context manager form of resolution. """ class LegacyRefResolver(object): @contextmanager def resolving(this, ref): self.assertEqual(ref, "the ref") yield {"type": "integer"} resolver = LegacyRefResolver() schema = {"$ref": "the ref"} with self.assertRaises(ValidationError): self.validator_class(schema, resolver=resolver).validate(None)
Example #10
Source File: test_cli.py From core with MIT License | 6 votes |
def test_unsuccessful_validation(self): error = ValidationError("I am an error!", instance=1) stdout, stderr = StringIO(), StringIO() exit_code = cli.run( { "validator": fake_validator([error]), "schema": {}, "instances": [1], "error_format": "{error.instance} - {error.message}", }, stdout=stdout, stderr=stderr, ) self.assertFalse(stdout.getvalue()) self.assertEqual(stderr.getvalue(), "1 - I am an error!") self.assertEqual(exit_code, 1)
Example #11
Source File: test_cli.py From core with MIT License | 6 votes |
def test_unsuccessful_validation_multiple_instances(self): first_errors = [ ValidationError("9", instance=1), ValidationError("8", instance=1), ] second_errors = [ValidationError("7", instance=2)] stdout, stderr = StringIO(), StringIO() exit_code = cli.run( { "validator": fake_validator(first_errors, second_errors), "schema": {}, "instances": [1, 2], "error_format": "{error.instance} - {error.message}\t", }, stdout=stdout, stderr=stderr, ) self.assertFalse(stdout.getvalue()) self.assertEqual(stderr.getvalue(), "1 - 9\t1 - 8\t2 - 7\t") self.assertEqual(exit_code, 1)
Example #12
Source File: poll_pods.py From social-relay with GNU Affero General Public License v3.0 | 6 votes |
def get_pod_relay_preferences(self, host): """Query remote pods on https first, fall back to http.""" logging.info("Querying %s" % host) try: try: response = requests.get("https://%s/.well-known/x-social-relay" % host, timeout=5, headers={"User-Agent": config.USER_AGENT}) except timeout: response = None if not response or response.status_code != 200: response = requests.get("http://%s/.well-known/x-social-relay" % host, timeout=5, headers={"User-Agent": config.USER_AGENT}) if response.status_code != 200: return None except (ConnectionError, Timeout, timeout): return None try: # Make sure we have a valid x-social-relay doc validate(response.json(), self.schema) return response.text except (ValueError, ValidationError): return None
Example #13
Source File: rest_service.py From scrapy-cluster with MIT License | 6 votes |
def validate_schema(schema_name): """Validate the JSON against a required schema_name.""" def decorator(f): @wraps(f) def wrapper(*args, **kw): instance = args[0] try: instance.validator(instance.schemas[schema_name]).validate(request.get_json()) except ValidationError, e: ret_dict = instance._create_ret_object(instance.FAILURE, None, True, instance.BAD_SCHEMA, e.message) instance.logger.error("Invalid Schema", ret_dict) return jsonify(ret_dict), 400 instance.logger.debug("Schema is valid") return f(*args, **kw) return wrapper
Example #14
Source File: test_core.py From pyungo with MIT License | 6 votes |
def test_schema(): from jsonschema import ValidationError schema = { "type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}, } graph = Graph(schema=schema) @graph.register(inputs=["a", "b"], outputs=["c"]) def f_my_function(a, b): return a + b with pytest.raises(ValidationError) as err: graph.calculate(data={"a": 1, "b": "2"}) msg = "'2' is not of type 'number'" assert msg in str(err.value) res = graph.calculate(data={"a": 1, "b": 2}) assert res == 3
Example #15
Source File: test_validation.py From babbage with MIT License | 5 votes |
def test_dimension_invalid_key(self, simple_model_data): with pytest.raises(ValidationError): model = simple_model_data model['dimensions']['foo']['key_attribute'] = 'lala' validate_model(model)
Example #16
Source File: test_schemas.py From senpy with Apache License 2.0 | 5 votes |
def do_create_(jsfile, success): def do_expected(self): with open(jsfile) as f: js = json.load(f) try: assert '@type' in js schema_name = js['@type'] with open(os.path.join(schema_folder, schema_name + ".json")) as file_object: schema = json.load(file_object) resolver = RefResolver('file://' + schema_folder + '/', schema) validator = Draft4Validator(schema, resolver=resolver) validator.validate(js) except (AssertionError, ValidationError, KeyError) as ex: if success: raise return assert success return do_expected
Example #17
Source File: utils.py From marvin-python-toolbox with Apache License 2.0 | 5 votes |
def validate_json(data, schema): if isinstance(data, str): data = from_json(data) if isinstance(schema, str): schema = from_json(schema) try: jsonschema.validate(data, schema) except jsonschema.ValidationError as e: raise InvalidJsonException(e.message)
Example #18
Source File: test_validation.py From babbage with MIT License | 5 votes |
def test_invalid_fact_table(self, simple_model_data): with pytest.raises(ValidationError): model = simple_model_data model['fact_table'] = 'b....' validate_model(model)
Example #19
Source File: security_keys.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_schema(self): file_path = find.data_file('security.json') self.assertIsNotNone(file_path, msg='failed to find the security.json file') with open(file_path, 'r') as file_h: key_store = serializers.JSON.load(file_h) try: utilities.validate_json_schema(key_store, 'king-phisher.security') except jsonschema.ValidationError: self.fail('the security.json file failed validation')
Example #20
Source File: test_config_verification.py From armory with MIT License | 5 votes |
def test_no_scenario(): with pytest.raises( jsonschema.ValidationError, match=r"'scenario' is a required property", ): load_config(str(pathlib.Path("tests/scenarios/broken/missing_scenario.json")))
Example #21
Source File: test_validator.py From os-net-config with Apache License 2.0 | 5 votes |
def test_consistent_error_messages_required(self): error = jsonschema.ValidationError( "%r is a required property" % u'name', validator=u'required') msg = validator._get_consistent_error_message(error) self.assertEqual(msg, "'name' is a required property") error = jsonschema.ValidationError( "u'name' is a required property", validator=u'required') msg = validator._get_consistent_error_message(error) self.assertEqual(msg, "'name' is a required property")
Example #22
Source File: test_validator.py From os-net-config with Apache License 2.0 | 5 votes |
def test_consistent_error_messages_oneOf(self): error = jsonschema.ValidationError( "%r is not one of %r" % (u'type', [u'vlan', u'interface']), validator=u'enum', validator_value=[u'vlan', u'interface'], instance=u'type') msg = validator._get_consistent_error_message(error) self.assertEqual(msg, "'type' is not one of ['vlan','interface']")
Example #23
Source File: test_validator.py From os-net-config with Apache License 2.0 | 5 votes |
def test_consistent_error_messages_type(self): error = jsonschema.ValidationError( "%r is not of type %r" % (u'name', u'string'), validator=u'type', validator_value=u'string', instance=u'name') msg = validator._get_consistent_error_message(error) self.assertEqual(msg, "'name' is not of type 'string'")
Example #24
Source File: rest_client.py From tempest-lib with Apache License 2.0 | 5 votes |
def validate_response(cls, schema, resp, body): # Only check the response if the status code is a success code # TODO(cyeoh): Eventually we should be able to verify that a failure # code if it exists is something that we expect. This is explicitly # declared in the V3 API and so we should be able to export this in # the response schema. For now we'll ignore it. if resp.status in HTTP_SUCCESS + HTTP_REDIRECTION: cls.expected_success(schema['status_code'], resp.status) # Check the body of a response body_schema = schema.get('response_body') if body_schema: try: jsonschema.validate(body, body_schema, cls=JSONSCHEMA_VALIDATOR, format_checker=FORMAT_CHECKER) except jsonschema.ValidationError as ex: msg = ("HTTP response body is invalid (%s)") % ex raise exceptions.InvalidHTTPResponseBody(msg) else: if body: msg = ("HTTP response body should not exist (%s)") % body raise exceptions.InvalidHTTPResponseBody(msg) # Check the header of a response header_schema = schema.get('response_header') if header_schema: try: jsonschema.validate(resp, header_schema, cls=JSONSCHEMA_VALIDATOR, format_checker=FORMAT_CHECKER) except jsonschema.ValidationError as ex: msg = ("HTTP response header is invalid (%s)") % ex raise exceptions.InvalidHTTPResponseHeader(msg)
Example #25
Source File: test_config_verification.py From armory with MIT License | 5 votes |
def test_invalid_dataset_framework(): with pytest.raises( jsonschema.ValidationError, match=r"is not one of \['tf', 'pytorch', 'numpy'\]", ): load_config( str(pathlib.Path("tests/scenarios/broken/invalid_dataset_framework.json")) )
Example #26
Source File: test_config_verification.py From armory with MIT License | 5 votes |
def test_invalid_module(): with pytest.raises( jsonschema.ValidationError, match=r"Failed validating 'pattern' in schema\[0\]\['properties'\]\['module'\]", ): load_config(str(pathlib.Path("tests/scenarios/broken/invalid_module.json")))
Example #27
Source File: patch.py From csvdiff with BSD 3-Clause "New" or "Revised" License | 5 votes |
def load(istream, strict=True): "Deserialize a patch object." try: diff = json.load(istream) if strict: jsonschema.validate(diff, SCHEMA) except ValueError: raise InvalidPatchError('patch is not valid JSON') except jsonschema.exceptions.ValidationError as e: raise InvalidPatchError(e.message) return diff
Example #28
Source File: patch.py From csvdiff with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_valid(diff): """ Validate the diff against the schema, returning True if it matches, False otherwise. """ try: validate(diff) except jsonschema.ValidationError: return False return True
Example #29
Source File: atlas.py From rucio with Apache License 2.0 | 5 votes |
def validate_schema(name, obj): """ Validate object against json schema :param name: The json schema name. :param obj: The object to validate. """ try: if obj: validate(obj, SCHEMAS.get(name, {})) except ValidationError as error: # NOQA, pylint: disable=W0612 raise InvalidObject("Problem validating %(name)s : %(error)s" % locals())
Example #30
Source File: test_validation.py From babbage with MIT License | 5 votes |
def test_invalid_dimension_name(self, simple_model_data): with pytest.raises(ValidationError): model = simple_model_data model['dimensions']['goo fdj.'] = {'label': 'bar'} validate_model(model)