diff --git a/src/xapi/tests/test_xapi_statement_validation.py b/src/xapi/tests/test_xapi_statement_validation.py index a1079271ac153d999eb8e6e9b434c4dbf53d9f8f..74fe11bc23dbcfe469abb573f5f7425514a1cd37 100644 --- a/src/xapi/tests/test_xapi_statement_validation.py +++ b/src/xapi/tests/test_xapi_statement_validation.py @@ -40,6 +40,32 @@ class TestxAPIStatementValidation(TestCase): except ValueError: assert False + def test_basic_valid_statement2000Times(self): + statement = { + "actor": { + "objectType": "Agent", + "name": "Gert Frobe", + "account": {"homePage": "http://example.adlnet.gov", "name": "1625378"}, + }, + "verb": { + "id": "http://adlnet.gov/expapi/verbs/failed", + "display": {"en-US": "failed"}, + }, + "object": { + "id": "https://example.adlnet.gov/AUidentifier", + "objectType": "Activity", + }, + } + + try: + cls = validator_for(self.schema) + cls.check_schema(self.schema) + instance = cls(self.schema) + for i in range(1, 2000): + instance.validate(statement) + except ValueError: + assert False + def test_validate_statement_with_uuid(self): statement = { "id": "e05aa883-acaf-40ad-bf54-02c8ce485fb0", diff --git a/src/xapi/views.py b/src/xapi/views.py index 8858ffbcbac23bc5e84dd06896c0869dc9790659..602d2b1327fa53c5a47e419900c48f45f74cc12d 100644 --- a/src/xapi/views.py +++ b/src/xapi/views.py @@ -9,6 +9,7 @@ from django.core.exceptions import ObjectDoesNotExist from django.http.response import JsonResponse from django.shortcuts import render from jsonschema import ValidationError, validate +from jsonschema.validators import validator_for from rest_framework import status from rest_framework.views import APIView @@ -23,7 +24,10 @@ from pathlib import Path PROJECT_PATH = os.path.abspath(os.path.dirname(__name__)) with open(os.path.join(PROJECT_PATH, "static/xapi_statement.schema.json")) as f: - schema = json.load(f) + schema = json.loads(f.read()) + cls = validator_for(schema) + cls.check_schema(schema) + instance = cls(schema) def store_in_db(x_api_statement): @@ -108,7 +112,7 @@ def process_statement(x_api_statement, provider, latest_schema): Process xAPI statement by checking for validation errors and user consent settings. """ try: - validate(x_api_statement, schema) + instance.validate(x_api_statement) except ValidationError as e: return {"valid": False, "accepted": False, "reason": e.message} @@ -232,7 +236,7 @@ def process_tan_statement(x_api_statement): Process xAPI statement by checking for validation errors. """ try: - validate(x_api_statement, schema) + instance.validate(x_api_statement) except ValidationError as e: return {"valid": False, "reason": e.message}