def validate_client_interaction(interaction): from enrolments.validators import validate_schema INTERACTION_SCHEMA = { "type": "str", "date": "str", "user_id": "int", } validate_schema(interaction, INTERACTION_SCHEMA) User = apps.get_model("accounts", "User") try: User.objects.get(id=interaction["user_id"]) except User.DoesNotExist as dne_error: raise dne_error except: raise ValidationError("Invalid interaction JSON")
def test_extra_field_strict(self): json = [ {"date": "2021-04-19", "attendees": [1, 2, 3]}, {"date": "2021-04-11", "attendees": [1, 2, 3], "extra": 20}, ] schema = [{"date": "str", "attendees": ["int"]}] self.assertFalse(validate_schema(json, schema, True))
def test_wrong_type(self): json = [ {"date": "2021-04-19", "attendees": [1, 2, 3]}, {"date": "2021-04-11", "attendees": [1, 2, 3]}, ] schema = [{"date": "str", "attendees": ["str"]}] self.assertFalse(validate_schema(json, schema))
def test_missing_list(self): json = [ {"date": "2021-04-19", "attendees": [1, 2, 3]}, {"date": "2021-04-11", "attendees": [1, 2, 3]}, ] schema = [{"date": "str", "attendees": "int"}] self.assertFalse(validate_schema(json, schema))
def test_simple_valid(self): json = [ {"date": "2021-04-19", "attendees": [1, 2, 3]}, {"date": "2021-04-11", "attendees": [1, 2, 3]}, ] schema = [{"date": "str", "attendees": ["int"]}] self.assertTrue(validate_schema(json, schema))
def test_nested(self): json = [ { "field1": [ { "field2": 30, "field3": ["str1", "str2", "str3"], "field4": [ {"field5": {"field6": [3.2, 3.1, 3.7], "field7": True}} ], } ], "field2": ["a", "b", "c"], "field3": -6, }, { "field1": [ { "field2": 2, "field3": ["asd", "qwe"], "field4": [ {"field5": {"field6": [1.0, 2.3, 1.2], "field7": False}}, {"field5": {"field6": [3.0, 4.0, 1.2], "field7": True}}, ], } ], "field2": [], "field3": 111, }, ] schema = [ { "field1": [ { "field2": "int", "field3": ["str"], "field4": [{"field5": {"field6": ["float"], "field7": "bool"}}], } ], "field2": ["str"], "field3": "int", } ] self.assertTrue(validate_schema(json, schema))