-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathmodel_validation.py
51 lines (38 loc) · 1.46 KB
/
model_validation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import yaml
from jsonschema import Draft7Validator, RefResolver, validators
API_FILENAME = "probeinfo_api.yaml"
with open(API_FILENAME, "r") as f:
API = yaml.load(f, Loader=yaml.SafeLoader)
SCHEMAS = API["components"]["schemas"]
RESOLVER = RefResolver("", API)
def extend_with_default(validator_class):
"""
Apply default values from the schema when not present.
See https://python-jsonschema.readthedocs.io/en/stable/faq/
"""
validate_properties = validator_class.VALIDATORS["properties"]
def set_defaults(validator, properties, instance, schema):
for property, subschema in properties.items():
if "default" in subschema:
instance.setdefault(property, subschema["default"])
for error in validate_properties(
validator,
properties,
instance,
schema,
):
yield error
return validators.extend(
validator_class,
{"properties": set_defaults},
)
Validator = extend_with_default(Draft7Validator)
def validate_as(instance, model_name):
schema = SCHEMAS[model_name]
Draft7Validator(schema, resolver=RESOLVER).validate(instance)
def apply_defaults_and_validate(instance, model_name):
schema = SCHEMAS[model_name]
Validator(schema, resolver=RESOLVER).validate(instance)
# Send through validation again to be sure any inject default values
# still validate with the schema.
validate_as(instance, model_name)