本文整理汇总了Python中jsonschema.ValidationError方法的典型用法代码示例。如果您正苦于以下问题:Python jsonschema.ValidationError方法的具体用法?Python jsonschema.ValidationError怎么用?Python jsonschema.ValidationError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jsonschema
的用法示例。
在下文中一共展示了jsonschema.ValidationError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validate
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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)
示例2: test_unsuccessful_validation
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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)
示例3: test_unsuccessful_validation_multiple_instances
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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)
示例4: test_it_delegates_to_a_legacy_ref_resolver
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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)
示例5: get_pod_relay_preferences
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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
示例6: test_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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
示例7: validate_schema
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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
示例8: type_draft3
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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,
)
示例9: oneOf_draft3
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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)
)
示例10: _validate_config
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
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}")
示例11: test_parse_invalid_jsonrpc
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
def test_parse_invalid_jsonrpc():
with pytest.raises(ValidationError):
parse('{"json": "2.0"}', batch=False)
示例12: validate_procfile
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
def validate_procfile(self, data):
for key, value in data.items():
if value is None or value == "":
raise serializers.ValidationError("Command can't be empty for process type")
if not re.match(PROCTYPE_MATCH, key):
raise serializers.ValidationError(PROCTYPE_MISMATCH_MSG)
return data
示例13: validate_memory
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
def validate_memory(self, data):
for key, value in data.items():
if value is None: # use NoneType to unset an item
continue
if not re.match(PROCTYPE_MATCH, key):
raise serializers.ValidationError(PROCTYPE_MISMATCH_MSG)
if not re.match(MEMLIMIT_MATCH, str(value)):
raise serializers.ValidationError(
"Memory limit format: <number><unit> or <number><unit>/<number><unit>, "
"where unit = B, K, M or G")
return data
示例14: validate_cpu
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
def validate_cpu(self, data):
for key, value in data.items():
if value is None: # use NoneType to unset an item
continue
if not re.match(PROCTYPE_MATCH, key):
raise serializers.ValidationError(PROCTYPE_MISMATCH_MSG)
shares = re.match(CPUSHARE_MATCH, str(value))
if not shares:
raise serializers.ValidationError(
"CPU limit format: <value> or <value>/<value>, where value must be a numeric")
return data
示例15: validate_tags
# 需要导入模块: import jsonschema [as 别名]
# 或者: from jsonschema import ValidationError [as 别名]
def validate_tags(self, data):
for key, value in data.items():
if value is None: # use NoneType to unset an item
continue
# split key into a prefix and name
if '/' in key:
prefix, name = key.split('/')
else:
prefix, name = None, key
# validate optional prefix
if prefix:
if len(prefix) > 253:
raise serializers.ValidationError(
"Tag key prefixes must 253 characters or less.")
for part in prefix.split('/'):
if not re.match(TAGVAL_MATCH, part):
raise serializers.ValidationError(
"Tag key prefixes must be DNS subdomains.")
# validate required name
if not re.match(TAGVAL_MATCH, name):
raise serializers.ValidationError(
"Tag keys must be alphanumeric or \"-_.\", and 1-63 characters.")
# validate value if it isn't empty
if value and not re.match(TAGVAL_MATCH, str(value)):
raise serializers.ValidationError(
"Tag values must be alphanumeric or \"-_.\", and 1-63 characters.")
return data