Python源码示例:jsonschema.exceptions()
示例1
def _validate_data(self, data: dict):
"""
Validates data against provider schema. Raises :class:`~notifiers.exceptions.BadArguments` if relevant
:param data: Data to validate
:raises: :class:`~notifiers.exceptions.BadArguments`
"""
log.debug("validating provided data")
e = best_match(self.validator.iter_errors(data))
if e:
custom_error_key = f"error_{e.validator}"
msg = (
e.schema[custom_error_key]
if e.schema.get(custom_error_key)
else e.message
)
raise BadArguments(validation_error=msg, provider=self.name, data=data)
示例2
def notify(self, raise_on_errors: bool = False, **kwargs) -> Response:
"""
The main method to send notifications. Prepares the data via the
:meth:`~notifiers.core.SchemaResource._prepare_data` method and then sends the notification
via the :meth:`~notifiers.core.Provider._send_notification` method
:param kwargs: Notification data
:param raise_on_errors: Should the :meth:`~notifiers.core.Response.raise_on_errors` be invoked immediately
:return: A :class:`~notifiers.core.Response` object
:raises: :class:`~notifiers.exceptions.NotificationError` if ``raise_on_errors`` is set to True and response
contained errors
"""
data = self._process_data(**kwargs)
rsp = self._send_notification(data)
if raise_on_errors:
rsp.raise_on_errors()
return rsp
示例3
def validate_output_parser(cls, value):
OPTIONS_VALIDATORS = {
'delimited': cls._validate_delimited_output_parser_options
}
schema = {
"type": "object",
"properties": {"type": {"type": "string",
"enum": ["delimited"]},
"options": {"type": "object"}
},
"required": ["type"]
}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
# Validate options specific to parser_type
if value.get('options'):
validate_options = OPTIONS_VALIDATORS[value.get('type')]
validate_options(value.get('options'))
示例4
def _validate_and_cache_nonfile(self, data):
value = data.get('_value_info')
type = data.get('type')
try:
self._cached_data_object = DataObject.objects.get(
uuid=data.get('uuid'))
self._do_create_new_data_object=False
self._verify_data_object_matches_data(self._cached_data_object, data)
return data
except DataObject.DoesNotExist:
pass
self._cached_data_object = DataObjectSerializer\
.Meta.model.get_by_value(value, type)
self._do_create_new_data_object=False # already saved
try:
self._cached_data_object.full_clean()
except django.core.exceptions.ValidationError as e:
raise serializers.ValidationError(e.message_dict)
return data
示例5
def _create_file(self, validated_data):
value = validated_data.pop('_value_info')
try:
self._cached_data_object.save()
# If file belongs to TaskAttemptLogFile, make the connection
log_file = self.context.get('task_attempt_log_file')
if log_file:
log_file.setattrs_and_save_with_retries({
'data_object': self._cached_data_object})
resource_init_args = copy.copy(value)
if self.context.get('task_attempt'):
resource_init_args['task_attempt'] = self.context.get(
'task_attempt')
resource_init_args['data_object'] = self._cached_data_object
file_resource = FileResource.initialize(**resource_init_args)
try:
file_resource.full_clean()
except django.core.exceptions.ValidationError as e:
raise serializers.ValidationError(e.message_dict)
file_resource.save()
return self._cached_data_object
except Exception as e:
self._cleanup(self._cached_data_object)
raise
示例6
def update(self, instance, validated_data):
# The only time a DataObject should be updated by the client
# is to change upload_status of a file.
value_data = validated_data.get('_value_info')
if value_data:
if not instance.type == 'file':
raise serializers.ValidationError(
'Updating value is not allowed on DataObject '\
'with type "%s"' % instance.type)
if not instance.value:
raise serializers.ValidationError(
"Failed to update DataObject because FileResource is missing")
try:
instance.value.setattrs_and_save_with_retries({
'upload_status': value_data.get('upload_status')})
except django.core.exceptions.ValidationError as e:
raise serializers.ValidationError(e.messages)
return instance
示例7
def raise_on_errors(self):
"""
Raises a :class:`~notifiers.exceptions.NotificationError` if response hold errors
:raises: :class:`~notifiers.exceptions.NotificationError`: If response has errors
"""
if self.errors:
raise NotificationError(
provider=self.provider,
data=self.data,
errors=self.errors,
response=self.response,
)
示例8
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
)
示例9
def _validate_data_dependencies(self, data: dict) -> dict:
"""
Validates specific dependencies based on the content of the data, as opposed to its structure which can be
verified on the schema level
:param data: Data to validate
:return: Return data if its valid
:raises: :class:`~notifiers.exceptions.NotifierException`
"""
return data
示例10
def test_valid_modification():
# Calls to validate() in this function should not raise exceptions
mod_types = ['Phosphorylation', 'Dephosphorylation', 'Ubiquitination',
'Deubiquitination', 'Sumoylation', 'Desumoylation',
'Hydroxylation', 'Dehydroxylation', 'Acetylation',
'Deacetylation', 'Glycosylation', 'Deglycosylation',
'Farnesylation', 'Defarnesylation', 'Geranylgeranylation',
'Degeranylgeranylation', 'Palmitoylation', 'Depalmitoylation',
'Myristoylation', 'Demyristoylation', 'Ribosylation',
'Deribosylation', 'Methylation', 'Demethylation',
'Activation', 'Inhibition', 'IncreaseAmount',
'DecreaseAmount']
for mod_type in mod_types:
s = {'enz': valid_agent1, 'sub': valid_agent2,
'type': mod_type, 'id': '5'}
jsonschema.validate([s], schema)
s['enz'] = agent_mod
jsonschema.validate([s], schema)
s['enz'] = agent_mut
jsonschema.validate([s], schema)
s['enz'] = agent_act
jsonschema.validate([s], schema)
if mod_type not in ['Activation', 'Inhibition', 'IncreaseAmount',
'DecreaseAmount']:
s['residue'] = 'S'
jsonschema.validate([s], schema)
s['position'] = '10'
jsonschema.validate([s], schema)
示例11
def _validate_boolean_data(cls, value):
schema = {"type": "object",
"properties": {"value": {"type": "boolean"}},
"required": ["value"]}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例12
def _validate_float_data(cls, value):
schema = {"type": "object",
"properties": {"value": {"type": "number"}},
"required": ["value"]}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例13
def _validate_integer_data(cls, value):
schema = {"type": "object",
"properties": {"value": {"type": "number"}},
"required": ["value"]}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例14
def _validate_string_data(cls, value):
schema = {"type": "object",
"properties": {"value": {"type": "string"}},
"required": ["value"]}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例15
def validate_environment(value):
schema = {
"type": "object",
"properties": {"docker_image": {"type": "string"}},
"required": ["docker_image"]
}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例16
def validate_notification_context(value):
schema = {
"type": "object",
"properties": {"server_name": {"type": "string"},
"server_url": {"type": "string"}},
"required": ["server_name"]
}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例17
def validate_data_path(value):
schema = {
"type": "array",
"items": {
"type": "array",
"items": [{"type": "integer"},
{"type": "integer"}]
}
}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)
示例18
def _cleanup(self, data_object):
try:
log_file = data_object.task_attempt_log_file
log_file.setattrs_and_save_with_retries({
'data_object': None})
except django.core.exceptions.ObjectDoesNotExist:
pass
data_object.delete()
示例19
def test_it__validation_failure__when_verbose_is_True():
UserKey = _makeModel()
schema = _makeSchema(UserKey)
uk = UserKey(key=1, keytype="*keytype*")
d = _callFUT(uk, schema, verbose=True)
assert d["deactivated_at"] is None
import jsonschema
from jsonschema.exceptions import ValidationError
with pytest.raises(ValidationError):
jsonschema.validate(d, schema)
示例20
def validate_outputs(cls, value):
schema = {
"type": "array",
"items": {
"type": "object",
"properties": {
"channel": {"type": "string"},
"as_channel": {"type": "string"},
"type": {
"type": "string",
"enum": ["file", "boolean", "string", "float", "integer"]},
"mode": {"type": "string"},
"source": {
"type": "object",
"properties": {
"stream": {"type": "string",
"enum": ["stdout", "stderr"]},
"filename": {"type": "string"},
"filenames": {
"oneOf": [
{"type": "string"},
{"type": "array",
"items": {"type": "string"}}
]},
"glob": {"type": "string"}
}
},
"parser": {
"type": "object",
"properties": {
"type": {"type": "string"},
"options": {"type": "object"}
}
}
},
"required" : ["type", "channel"]
}
}
try:
jsonschema.validate(value, schema)
except jsonschema.exceptions.ValidationError as e:
raise ValidationError(e.message)