diff --git a/SAS/TMSS/src/tmss/tmssapp/models/scheduling.py b/SAS/TMSS/src/tmss/tmssapp/models/scheduling.py index 7693d05da21a9033ddefb55cbdeda5278fede3e4..f52967a410e9053ee8704bdaf260039a591f2560 100644 --- a/SAS/TMSS/src/tmss/tmssapp/models/scheduling.py +++ b/SAS/TMSS/src/tmss/tmssapp/models/scheduling.py @@ -153,12 +153,19 @@ class Subtask(BasicCommon): # resource_claim = ForeignKey("ResourceClaim", null=False, on_delete=PROTECT) # todo <-- how is this external reference supposed to work? def validate_specification_against_schema(self): + if self.specifications_doc is None or self.specifications_template_id is None: + return + try: # ensure the specification and schema are both valid json in the first place spec = json.loads(self.specifications_doc) if type(self.specifications_doc) == str else self.specifications_doc schema = json.loads(self.specifications_template.schema) if type(self.specifications_template.schema) == str else self.specifications_template.schema + except json.decoder.JSONDecodeError as e: + raise SpecificationException("Invalid JSON: %s" % str(e)) + + try: jsonschema.validate(spec, schema) - except Exception as e: + except jsonschema.ValidationError as e: raise SpecificationException(str(e)) def save(self, force_insert=False, force_update=False, using=None, update_fields=None): diff --git a/SAS/TMSS/test/t_subtask_validation.py b/SAS/TMSS/test/t_subtask_validation.py index a213de90a6c1e517bf26b18df3ff4d7e1600e9bf..e156ffd4f78eba362a167703052e361438cd3e5a 100755 --- a/SAS/TMSS/test/t_subtask_validation.py +++ b/SAS/TMSS/test/t_subtask_validation.py @@ -86,6 +86,25 @@ class SubtaskValidationTest(unittest.TestCase): subtask = models.Subtask.objects.create(**subtask_data) self.assertIsNotNone(subtask) + def test_validate_flawed_json_schema(self): + subtask_template = self.create_subtask_template('{ this is not a json object }') + specifications_doc = '"a random string"' + subtask_data = Subtask_test_data(subtask_template, specifications_doc) + + with self.assertRaises(SpecificationException) as context: + models.Subtask.objects.create(**subtask_data) + self.assertTrue('invalid json' in str(context.exception).lower()) + + def test_validate_flawed_json_specification(self): + subtask_template = self.create_subtask_template('{"type": "string"}') + specifications_doc = '{ this is not a json object }' + subtask_data = Subtask_test_data(subtask_template, specifications_doc) + + with self.assertRaises(SpecificationException) as context: + models.Subtask.objects.create(**subtask_data) + self.assertTrue('invalid json' in str(context.exception).lower()) + + if __name__ == "__main__": os.environ['TZ'] = 'UTC' unittest.main()