Browse Source

Handle "required" keyword.

pull/114/merge
Pēteris Caune 8 years ago
parent
commit
eece7c7551
2 changed files with 13 additions and 1 deletions
  1. +6
    -1
      hc/lib/jsonschema.py
  2. +7
    -0
      hc/lib/tests/test_jsonschema.py

+ 6
- 1
hc/lib/jsonschema.py View File

@ -47,10 +47,15 @@ def validate(obj, schema, obj_name="value"):
if not isinstance(obj, dict): if not isinstance(obj, dict):
raise ValidationError("%s is not an object" % obj_name) raise ValidationError("%s is not an object" % obj_name)
for key, spec in schema["properties"].items():
properties = schema.get("properties", {})
for key, spec in properties.items():
if key in obj: if key in obj:
validate(obj[key], spec, obj_name=key) validate(obj[key], spec, obj_name=key)
for key in schema.get("required", []):
if key not in obj:
raise ValidationError("key %s absent in %s" % (key, obj_name))
if "enum" in schema: if "enum" in schema:
if obj not in schema["enum"]: if obj not in schema["enum"]:
raise ValidationError("%s has unexpected value" % obj_name) raise ValidationError("%s has unexpected value" % obj_name)

+ 7
- 0
hc/lib/tests/test_jsonschema.py View File

@ -52,6 +52,13 @@ class JsonSchemaTestCase(TestCase):
} }
}) })
def test_it_handles_required_properties(self):
with self.assertRaises(ValidationError):
validate({"foo": "bar"}, {
"type": "object",
"required": ["baz"]
})
def test_it_validates_arrays(self): def test_it_validates_arrays(self):
validate(["foo", "bar"], { validate(["foo", "bar"], {
"type": "array", "type": "array",


Loading…
Cancel
Save