本文整理汇总了Python中jsonschema.SchemaError方法的典型用法代码示例。如果您正苦于以下问题:Python jsonschema.SchemaError方法的具体用法?Python jsonschema.SchemaError怎么用?Python jsonschema.SchemaError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jsonschema
的用法示例。
在下文中一共展示了jsonschema.SchemaError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_validator
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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)
示例2: validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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))
示例3: test_register_invalid_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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
})
示例4: check_install_json
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
def check_install_json(self):
"""Check all install.json files for valid schema."""
if self.install_json_schema is None:
return
contents = os.listdir(self.app_path)
if self.args.install_json is not None:
contents = [self.args.install_json]
for install_json in sorted(contents):
# skip files that are not install.json files
if 'install.json' not in install_json:
continue
error = None
status = True
try:
# loading explicitly here to keep all error catching in this file
with open(install_json) as fh:
data = json.loads(fh.read())
validate(data, self.install_json_schema)
except SchemaError as e:
status = False
error = e
except ValidationError as e:
status = False
error = e.message
except ValueError:
# any JSON decode error will be caught during syntax validation
return
if error:
# update validation data errors
self.validation_data['errors'].append(
f'Schema validation failed for {install_json} ({error}).'
)
# update validation data for module
self.validation_data['schema'].append({'filename': install_json, 'status': status})
示例5: check_layout_json
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
def check_layout_json(self):
"""Check all layout.json files for valid schema."""
# the install.json files can't be validates if the schema file is not present
layout_json_file = 'layout.json'
if self.layout_json_schema is None or not os.path.isfile(layout_json_file):
return
error = None
status = True
try:
# loading explicitly here to keep all error catching in this file
with open(layout_json_file) as fh:
data = json.loads(fh.read())
validate(data, self.layout_json_schema)
except SchemaError as e:
status = False
error = e
except ValidationError as e:
status = False
error = e.message
except ValueError:
# any JSON decode error will be caught during syntax validation
return
# update validation data for module
self.validation_data['schema'].append({'filename': layout_json_file, 'status': status})
if error:
# update validation data errors
self.validation_data['errors'].append(
f'Schema validation failed for {layout_json_file} ({error}).'
)
else:
self.check_layout_params()
示例6: test_schema_load_failure_bad_file
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
def test_schema_load_failure_bad_file(self):
""" Test Exception raise on not existent file load. """
schemaproc = val.SchemaProcessor()
schema = os.path.join('not', 'a', 'valid', 'path.json')
nose.tools.assert_raises(
jsonschema.SchemaError,
schemaproc.load, schema
)
示例7: test_schema_load_failure_no_json_object
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
def test_schema_load_failure_no_json_object(self):
test_file_path = '/tmp/test.json'
open(test_file_path, 'w').close()
schemaproc = val.SchemaProcessor()
nose.tools.assert_raises(
jsonschema.SchemaError,
schemaproc.load, test_file_path
)
os.remove(test_file_path)
示例8: load
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
def load(self, schemafile=None):
"""Load and process the schema file"""
if schemafile is not None:
self._schemafile = schemafile
try:
self.data = json.load(open(self._schemafile))
except (IOError, ValueError) as e:
msg = "Could not load schema file '" + self._schemafile + "': '" + str(e) + "'"
raise jsonschema.SchemaError(msg)
self.loaded = True
示例9: schema_val
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
def schema_val(self, messages=None):
"Perform validation with processed YAML and Schema"
self._ymlproc = YAMLProcessor(self._ymlfile)
self._schemaproc = SchemaProcessor(self._schemafile)
valid = True
log.debug("BEGIN: Schema-based validation for YAML '%s' with schema '%s'", self._ymlfile, self._schemafile)
# Make sure the yml and schema have been loaded
if self._ymlproc.loaded and self._schemaproc.loaded:
# Load all of the yaml documents. Could be more than one in the same YAML file.
for docnum, data in enumerate(yaml.load_all(self._ymlproc.data, Loader=yaml.Loader)):
# Since YAML allows integer keys but JSON does not, we need to first
# dump the data as a JSON string to encode all of the potential integers
# as strings, and then read it back out into the YAML format. Kind of
# a clunky workaround but it works as expected.
data = yaml.load(json.dumps(data), Loader=yaml.Loader)
# Now we want to get a validator ready
v = jsonschema.Draft4Validator(self._schemaproc.data)
# Loop through the errors (if any) and set valid = False if any are found
# Display the error message
for error in sorted(v.iter_errors(data)):
msg = "Schema-based validation failed for YAML file '" + self._ymlfile + "'"
self.ehandler.process(docnum, self._ymlproc.doclines, error, messages)
valid = False
if not valid:
log.error(msg)
elif not self._ymlproc.loaded:
raise util.YAMLError("YAML must be loaded in order to validate.")
elif not self._schemaproc.loaded:
raise jsonschema.SchemaError("Schema must be loaded in order to validate.")
log.debug("END: Schema-based validation complete for '%s'", self._ymlfile)
return valid
示例10: main
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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
示例11: validate_against_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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
示例12: _validate_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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
)
示例13: test_inference_options_invalid_shema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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)
示例14: test_register_invalid
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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'
}
}
})
示例15: app_validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import SchemaError [as 别名]
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")