From 05fcf7fcedb99775024e285902d7a7af4a83c137 Mon Sep 17 00:00:00 2001 From: Jorrit Schaap <schaap@astron.nl> Date: Tue, 11 Feb 2020 15:42:52 +0100 Subject: [PATCH] TMSS-142: check for valid json --- .../src/tmss/tmssapp/models/scheduling.py | 9 ++++++++- SAS/TMSS/test/t_subtask_validation.py | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/SAS/TMSS/src/tmss/tmssapp/models/scheduling.py b/SAS/TMSS/src/tmss/tmssapp/models/scheduling.py index 7693d05da21..f52967a410e 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 a213de90a6c..e156ffd4f78 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() -- GitLab