diff --git a/hc/lib/jsonschema.py b/hc/lib/jsonschema.py index 692a6661..7653b057 100644 --- a/hc/lib/jsonschema.py +++ b/hc/lib/jsonschema.py @@ -47,10 +47,15 @@ def validate(obj, schema, obj_name="value"): if not isinstance(obj, dict): 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: 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 obj not in schema["enum"]: raise ValidationError("%s has unexpected value" % obj_name) diff --git a/hc/lib/tests/test_jsonschema.py b/hc/lib/tests/test_jsonschema.py index f0ff72dd..d51a120c 100644 --- a/hc/lib/tests/test_jsonschema.py +++ b/hc/lib/tests/test_jsonschema.py @@ -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): validate(["foo", "bar"], { "type": "array",