From eece7c7551e59f62d28847b8898d96a430aacef4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= Date: Thu, 11 May 2017 12:54:58 +0300 Subject: [PATCH] Handle "required" keyword. --- hc/lib/jsonschema.py | 7 ++++++- hc/lib/tests/test_jsonschema.py | 7 +++++++ 2 files changed, 13 insertions(+), 1 deletion(-) 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",