-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathe_custom_json_schema_validations.py
65 lines (58 loc) · 1.91 KB
/
e_custom_json_schema_validations.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from injecty import get_default_injecty_context
from jsonschema import ValidationError
from schemey.json_schema.schema_validator_abc import SchemaValidatorABC
from schemey.validator import validator_from_json
class UniqueNamesValidator(SchemaValidatorABC):
property_name = "uniqueNames"
def validate(self, validator, aP, instance, schema):
"""
A custom validator that ensures that values for the name attribute for items in an array are unique.
"""
# if not validator.is_type(instance, "array"):
# return
# if not schema.get("uniqueNames"):
# return
names = set()
for item in instance:
# if not validator.is_type(item, "object"):
# continue # We assume that type validations are handled elsewhere
name = item.get("name")
# if not isinstance(name, str):
# continue
if name in names:
yield ValidationError(
f"Duplicate Name: {name}",
validator=validator,
validator_value=aP,
instance=instance,
schema=schema,
)
names.add(name)
# We register the validator we just defined
get_default_injecty_context().register_impl(SchemaValidatorABC, UniqueNamesValidator)
json_schema = {
"type": "array",
"uniqueNames": True,
"items": {
"name": "SomeNamedItem",
"type": "object",
"properties": {"name": {"type": "string"}},
"additionalProperties": False,
},
}
validator = validator_from_json(json_schema)
validator.validate(
[
{"name": "Bill"},
{"name": "Ted"},
]
)
errors = list(
validator.iter_errors(
[
{"name": "Bill"},
{"name": "Bill"},
]
)
)
print(errors) # There should be an error here since the name "Bill" is duplicated!