jsonschema: add support for default values (#36133)
This commit is contained in:
parent
572edbb589
commit
62f9fef48a
|
@ -0,0 +1,25 @@
|
|||
from jsonschema import validators, ValidationError
|
||||
from jsonschema import validate as jsonschema_validate
|
||||
|
||||
def extend_with_default(validator_class):
|
||||
validate_properties = validator_class.VALIDATORS["properties"]
|
||||
|
||||
def set_defaults(validator, properties, instance, schema):
|
||||
if isinstance(instance, bool):
|
||||
return
|
||||
for property, subschema in properties.items():
|
||||
if isinstance(subschema, bool):
|
||||
continue
|
||||
if "default" in subschema:
|
||||
instance.setdefault(property, subschema["default"])
|
||||
|
||||
return validators.extend(
|
||||
validator_class, {"properties" : set_defaults},
|
||||
)
|
||||
|
||||
|
||||
def validate(instance, schema, cls=None, *args, **kwargs):
|
||||
validator_class = validators.validator_for(schema)
|
||||
validator_class_with_defaults = extend_with_default(validator_class)
|
||||
return jsonschema_validate(instance, schema, validator_class_with_defaults,
|
||||
*args, **kwargs)
|
|
@ -42,12 +42,12 @@ from django.forms.models import modelform_factory
|
|||
from django.forms.widgets import ClearableFileInput
|
||||
|
||||
from dateutil import parser as date_parser
|
||||
from jsonschema import validate, ValidationError
|
||||
|
||||
from passerelle.base.models import BaseResource, ResourceLog
|
||||
from passerelle.utils.jsonresponse import APIError
|
||||
|
||||
from .utils import to_json, is_authorized
|
||||
from .utils.json_schema import validate, ValidationError
|
||||
from .forms import GenericConnectorForm
|
||||
|
||||
if 'mellon' in settings.INSTALLED_APPS:
|
||||
|
|
|
@ -0,0 +1,40 @@
|
|||
from passerelle.utils.json_schema import validate
|
||||
|
||||
|
||||
def test_validators_with_default_values():
|
||||
schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"string": {
|
||||
"type": "string",
|
||||
"default": "default"
|
||||
},
|
||||
"integer": {
|
||||
"type": "integer",
|
||||
"default": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
obj = {}
|
||||
validate(obj, schema)
|
||||
assert obj == {"string": "default", "integer": 0}
|
||||
|
||||
|
||||
def test_legacy_validators_with_default_values():
|
||||
schema = {
|
||||
"$schema": "http://json-schema.org/draft-03/schema#",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"string": {
|
||||
"type": "string",
|
||||
"default": "text"
|
||||
},
|
||||
"integer": {
|
||||
"type": "integer",
|
||||
"default": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
new_obj = {}
|
||||
validate(new_obj, schema)
|
||||
assert new_obj == {"string": "text", "integer": 0}
|
Loading…
Reference in New Issue