From f8d6364fb4aa7e3fbd768a1b752ca924ea4edc5a Mon Sep 17 00:00:00 2001 From: Feanil Patel Date: Thu, 19 Nov 2026 15:56:43 -0500 Subject: [PATCH 1/4] feat!: remove the MATLAB API key and the ungraded_response handler The MATLAB integration sent code to the MathWorks hosted service through the XQueue service and got results back on the XQueue callback URL. Neither exists any more, and xblocks-core has dropped MatlabInput and the matlab_api_key argument to LoncapaSystem (https://github.com/openedx/xblocks-core/pull/338). https://github.com/openedx/public-engineering/issues/192 deprecated the MATLAB handling in 2023 because the endpoint it talked to no longer worked. Remove the matlab_api_key field from ProblemBlock and from the inheritance mixin that put it on the course's Advanced Settings, the ungraded_response ajax handler that carried MATLAB's plot output, and the MATLAB wording on the Studio import and export pages. The cms tests that used matlab_api_key as a sample settings field use source_code instead. Existing problems still parse: xblocks-core keeps the tag on CodeInput so learners keep their scores. BREAKING CHANGE: the "Matlab API key" advanced setting is gone from courses and problems. Course exports that carry matlab_api_key still import, and the key is kept as an unrecognized attribute and written back out on export, like any other attribute the platform does not know. Co-Authored-By: Claude Fable 5.1 --- .../tests/test_downstream_sync_integration.py | 1 - .../contentstore/tests/test_export_git.py | 2 +- cms/lib/xblock/test/test_upstream_sync.py | 10 ++--- cms/templates/export.html | 6 +-- cms/templates/import.html | 2 +- xmodule/capa_block.py | 44 +------------------ xmodule/modulestore/inheritance.py | 9 ---- 7 files changed, 11 insertions(+), 63 deletions(-) diff --git a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py index ffa8b0fa7089..984d9d87c5eb 100644 --- a/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py +++ b/cms/djangoapps/contentstore/rest_api/v2/views/tests/test_downstream_sync_integration.py @@ -168,7 +168,6 @@ def assertXmlEqual(self, xml_str_a: str, xml_str_b: str) -> None: # OLX attributes that will appear on capa problems when saved/exported. Excludes "markdown" standard_capa_attributes = """ markdown_edited="false" - matlab_api_key="null" name="null" rerandomize="never" source_code="null" diff --git a/cms/djangoapps/contentstore/tests/test_export_git.py b/cms/djangoapps/contentstore/tests/test_export_git.py index a986b342041d..1556d641f470 100644 --- a/cms/djangoapps/contentstore/tests/test_export_git.py +++ b/cms/djangoapps/contentstore/tests/test_export_git.py @@ -126,7 +126,7 @@ def test_dirty_repo(self): self.course_block.giturl, self.user) # Make arbitrary change to course to make diff - self.course_block.matlab_api_key = 'something' + self.course_block.display_name = 'something' modulestore().update_item(self.course_block, self.user.id) # Touch a file in the directory, export again, and make sure # the test file is gone diff --git a/cms/lib/xblock/test/test_upstream_sync.py b/cms/lib/xblock/test/test_upstream_sync.py index d32f2fb5809a..cc0069bb14c1 100644 --- a/cms/lib/xblock/test/test_upstream_sync.py +++ b/cms/lib/xblock/test/test_upstream_sync.py @@ -63,12 +63,12 @@ def setUp(self): ' force_save_button="false"' ' graceperiod="1d"' ' grading_method="last_attempt"' - ' matlab_api_key="abc"' ' max_attempts="10"' ' rerandomize=""always""' ' show_correctness="never"' ' show_reset_button="false"' ' showanswer="on_correct"' + ' source_code="abc"' ' submission_wait_seconds="10"' ' use_latex_compiler="false"' ' weight="1"' @@ -250,7 +250,7 @@ def test_sync_updates_to_downstream_only_fields(self): assert downstream.upstream_display_name == "Upstream Problem Title V2" assert downstream.display_name == "Upstream Problem Title V2" assert downstream.rerandomize == '"always"' - assert downstream.matlab_api_key == 'abc' + assert downstream.source_code == 'abc' assert not downstream.use_latex_compiler # These fields are "downstream only", so field defaults are preserved, and values are NOT copied from upstream @@ -275,12 +275,12 @@ def test_sync_updates_to_downstream_only_fields(self): ' force_save_button="false"' ' graceperiod=""' ' grading_method="final_attempt"' - ' matlab_api_key="def"' ' max_attempts="11"' ' rerandomize=""per_student""' ' show_correctness="past_due"' ' show_reset_button="false"' ' showanswer="attempted"' + ' source_code="def"' ' submission_wait_seconds="11"' ' use_latex_compiler="true"' ' weight="2"' @@ -304,7 +304,7 @@ def test_sync_updates_to_downstream_only_fields(self): # Modifying synchronized fields are "unsafe" customizations downstream.rerandomize = '"onreset"' - downstream.matlab_api_key = 'hij' + downstream.source_code = 'hij' save_xblock_with_callback(downstream, self.user) # Follow-up sync. @@ -313,7 +313,7 @@ def test_sync_updates_to_downstream_only_fields(self): # "unsafe" customizations are overridden by upstream assert downstream.upstream_display_name == "Upstream Problem Title V3" assert downstream.rerandomize == '"per_student"' - assert downstream.matlab_api_key == 'def' + assert downstream.source_code == 'def' assert downstream.use_latex_compiler # but "safe" customizations survive diff --git a/cms/templates/export.html b/cms/templates/export.html index 44922b5eedb7..d5872c25dc4e 100644 --- a/cms/templates/export.html +++ b/cms/templates/export.html @@ -48,7 +48,7 @@

${_("About Exporting Courses")}

${_("You can export courses and edit them outside of {studio_name}. The exported file is a .tar.gz file (that is, a .tar file compressed with GNU Zip) that contains the course structure and content. You can also re-import courses that you've exported.").format( studio_name=settings.STUDIO_SHORT_NAME )}

-

${Text(_("{em_start}Caution:{em_end} When you export a course, information such as MATLAB API keys, LTI passports, annotation secret token strings, and annotation storage URLs are included in the exported data. If you share your exported files, you may also be sharing sensitive or license-specific information.")).format( +

${Text(_("{em_start}Caution:{em_end} When you export a course, information such as LTI passports, annotation secret token strings, and annotation storage URLs are included in the exported data. If you share your exported files, you may also be sharing sensitive or license-specific information.")).format( em_start=HTML(''), em_end=HTML("") )}

@@ -151,7 +151,7 @@

em_end=HTML("") )}

    -
  • ${_("Values from Advanced Settings, including MATLAB API keys and LTI passports")}
  • +
  • ${_("Values from Advanced Settings, including LTI passports")}
  • ${_("Course Content (all Sections, Sub-sections, and Units)")}
  • ${_("Course Structure")}
  • ${_("Individual Problems")}
  • @@ -192,7 +192,7 @@

    ${_("What content is exported?")}

  • ${_("Course dates")}
  • ${_("Grading policy")}
  • ${_("Any group configurations")}
  • -
  • ${_("Settings on the Advanced Settings page, including MATLAB API keys and LTI passports")}
  • +
  • ${_("Settings on the Advanced Settings page, including LTI passports")}

${_("The following content is not exported.")}

    diff --git a/cms/templates/import.html b/cms/templates/import.html index a711a845c4c0..638f209b9e61 100644 --- a/cms/templates/import.html +++ b/cms/templates/import.html @@ -169,7 +169,7 @@

    ${_("What content is imported?")}

  • ${_("Course dates")}
  • ${_("Grading policy")}
  • ${_("Any group configurations")}
  • -
  • ${_("Settings on the Advanced Settings page, including MATLAB API keys and LTI passports")}
  • +
  • ${_("Settings on the Advanced Settings page, including LTI passports")}

${_("The following content is not imported.")}

    diff --git a/xmodule/capa_block.py b/xmodule/capa_block.py index 770053f04161..2862649ffc4f 100644 --- a/xmodule/capa_block.py +++ b/xmodule/capa_block.py @@ -331,17 +331,6 @@ class _BuiltInProblemBlock( # pylint: disable=too-many-public-methods,too-many- help=_("Source code for LaTeX and Word problems. This feature is not well-supported."), scope=Scope.settings ) use_latex_compiler = Boolean(help=_("Enable LaTeX templates?"), default=False, scope=Scope.settings) - matlab_api_key = String( - display_name=_("Matlab API key"), - help=_( - "Enter the API key provided by MathWorks for accessing the MATLAB Hosted Service. " - "This key is granted for exclusive use by this course for the specified duration. " - "Please do not share the API key with other courses and notify MathWorks immediately " - "if you believe the key is exposed or compromised. To obtain a key for your course, " - "or to report an issue, please contact moocsupport@mathworks.com" - ), - scope=Scope.settings, - ) markdown_edited = Boolean( help=_("Indicates if the problem was edited using the Markdown editor in the Authoring MFE."), scope=Scope.settings, @@ -416,7 +405,6 @@ def handle_ajax(self, dispatch, data): # pylint: disable=too-many-locals "problem_show": self.get_answer, "score_update": self.update_score, "input_ajax": self.handle_input_ajax, - "ungraded_response": self.handle_ungraded_response, } _ = self.runtime.service(self, "i18n").gettext @@ -543,10 +531,6 @@ def non_editable_metadata_fields(self): ProblemBlock.markdown, ProblemBlock.use_latex_compiler, ProblemBlock.show_correctness, - # Temporarily remove the ability to see MATLAB API key in Studio, as - # a pre-cursor to removing it altogether. - # https://github.com/openedx/public-engineering/issues/192 - ProblemBlock.matlab_api_key, ] ) return non_editable_fields @@ -640,7 +624,6 @@ def max_score(self): resources_fs=self.runtime.resources_fs, seed=None, xqueue=None, - matlab_api_key=None, ) try: lcp = LoncapaProblem( @@ -687,7 +670,7 @@ def generate_report_data(self, user_state_iterator, limit_responses=None): capa_system = LoncapaSystem( ajax_url=None, # TODO set anonymous_student_id to the anonymous ID of the user which answered each problem - # Anonymous ID is required for Matlab, CodeResponse, and some custom problems that include + # Anonymous ID is required for CodeResponse and some custom problems that include # '$anonymous_student_id' in their XML. # For the purposes of this report, we don't need to support those use cases. anonymous_student_id=None, @@ -700,7 +683,6 @@ def generate_report_data(self, user_state_iterator, limit_responses=None): resources_fs=self.runtime.resources_fs, seed=1, xqueue=None, - matlab_api_key=None, ) _ = capa_system.i18n.gettext @@ -864,7 +846,6 @@ def new_lcp(self, state, text=None): resources_fs=self.runtime.resources_fs, seed=seed, # Why do we do this if we have self.seed? xqueue=None if is_studio else xqueue_service, - matlab_api_key=self.matlab_api_key, ) return LoncapaProblem( @@ -1541,29 +1522,6 @@ def update_score(self, data): return {} # No AJAX return is needed - def handle_ungraded_response(self, data): - """ - Delivers a response from the XQueue to the capa problem - - The score of the problem will not be updated - - Args: - - data (dict) must contain keys: - queuekey - a key specific to this response - xqueue_body - the body of the response - Returns: - empty dictionary - - No ajax return is needed, so an empty dict is returned - """ - queuekey = data["queuekey"] - score_msg = data["xqueue_body"] - - # pass along the xqueue message to the problem - self.lcp.ungraded_response(score_msg, queuekey) - self.set_state_from_lcp() - return {} - def handle_input_ajax(self, data): """ Handle ajax calls meant for a particular input in the problem diff --git a/xmodule/modulestore/inheritance.py b/xmodule/modulestore/inheritance.py index 3968972d1888..6362ef731a38 100644 --- a/xmodule/modulestore/inheritance.py +++ b/xmodule/modulestore/inheritance.py @@ -147,15 +147,6 @@ class InheritanceMixin(XBlockMixin): help=_("Enter the maximum number of times a student can try to answer problems. By default, Maximum Attempts is set to null, meaning that students have an unlimited number of attempts for problems. You can override this course-wide setting for individual problems. However, if the course-wide setting is a specific number, you cannot set the Maximum Attempts for individual problems to unlimited."), # pylint: disable=line-too-long values={"min": 0}, scope=Scope.settings ) - matlab_api_key = String( - display_name=_("Matlab API key"), - help=_("Enter the API key provided by MathWorks for accessing the MATLAB Hosted Service. " - "This key is granted for exclusive use in this course for the specified duration. " - "Do not share the API key with other courses. Notify MathWorks immediately " - "if you believe the key is exposed or compromised. To obtain a key for your course, " - "or to report an issue, please contact moocsupport@mathworks.com"), - scope=Scope.settings - ) # This is should be scoped to content, but since it's defined in the policy # file, it is currently scoped to settings. user_partitions = UserPartitionList( From ebe22ffce55836e5fa455219776230efa1f10b19 Mon Sep 17 00:00:00 2001 From: Feanil Patel Date: Thu, 19 Nov 2026 15:58:58 -0500 Subject: [PATCH 2/4] feat!: remove the XQueue service settings, callback URL and waffle flag The XQueue service is deprecated and its repo archived (https://github.com/openedx/public-engineering/issues/286). The LMS queues external grader submissions in edx-submissions and serves the API that xqueue-watcher polls, and scores come back through the EXTERNAL_GRADER_SCORE_SUBMITTED signal. Nothing posts to the service any more: xblocks-core's XQueueInterface only hands submissions to edx-submissions (https://github.com/openedx/xblocks-core/pull/338). Remove what only existed for the service: the XQUEUE_INTERFACE setting and its mock and test values, XQUEUE_PORT, the xqueue_callback view and its two URL patterns, XQueueService's HTTP setup and construct_callback, and the send_to_submission_course.enable course flag that picked between the two backends. XQUEUE_WAITTIME_BETWEEN_REQUESTS stays: it is the wait a learner has to observe between submissions to a queued problem. BREAKING CHANGE: XQUEUE_INTERFACE is no longer read. The send_to_submission_course.enable waffle flag is gone; every course's external grader submissions now go to edx-submissions. The /courses//xqueue/// callback URL is gone. Drain the XQueue server before upgrading: a result for a submission still queued there has no callback URL to come back to. Co-Authored-By: Claude Fable 5.1 --- cms/envs/mock.yml | 8 -- lms/djangoapps/courseware/block_render.py | 49 +--------- .../courseware/tests/test_block_render.py | 88 ------------------ .../tests/test_submitting_problems.py | 39 +++++--- lms/djangoapps/grades/signals/handlers.py | 3 +- lms/envs/mock.yml | 8 -- lms/envs/test.py | 8 -- lms/urls.py | 17 ---- .../core/djangoapps/xblock/runtime/shims.py | 1 - openedx/envs/common.py | 10 +- openedx/envs/test.py | 1 - xmodule/services.py | 69 +------------- xmodule/tests/test_capa_block.py | 93 +++++-------------- xmodule/tests/test_services.py | 41 +------- 14 files changed, 66 insertions(+), 369 deletions(-) diff --git a/cms/envs/mock.yml b/cms/envs/mock.yml index c45e37d023d3..9a236461d68c 100644 --- a/cms/envs/mock.yml +++ b/cms/envs/mock.yml @@ -770,14 +770,6 @@ XBLOCK_SETTINGS: ScormXBlock: S3_BUCKET_NAME: scorm STORAGE_FUNC: storage.s3 -XQUEUE_INTERFACE: - basic_auth: - - user - - pass - django_auth: - password: pass - username: user - url: https://xqueue.localhost YOUTUBE_API_KEY: test_youtube ZENDESK_API_KEY: test_zendesk ZENDESK_CUSTOM_FIELDS: diff --git a/lms/djangoapps/courseware/block_render.py b/lms/djangoapps/courseware/block_render.py index e3ea6a288902..32699bbc9276 100644 --- a/lms/djangoapps/courseware/block_render.py +++ b/lms/djangoapps/courseware/block_render.py @@ -16,7 +16,7 @@ from django.contrib.auth.models import AnonymousUser, User # pylint: disable=imported-auth-user from django.core.cache import cache from django.db import transaction -from django.http import Http404, HttpResponse, HttpResponseForbidden +from django.http import Http404, HttpResponseForbidden from django.middleware.csrf import CsrfViewMiddleware from django.template.context_processors import csrf from django.urls import reverse @@ -662,6 +662,10 @@ def inner_get_block(block: XBlock) -> XBlock | None: def load_single_xblock(request, user_id, course_id, usage_key_string, course=None, will_recheck_access=False): """ Load a single XBlock identified by usage_key_string. + + Nothing in the platform calls this outside of tests since the xqueue_callback view + was removed. It stays for the feedback block in xblocks-extra until both callers + move off it: https://github.com/openedx/openedx-platform/issues/39434 """ usage_key = UsageKey.from_string(usage_key_string) course_key = CourseKey.from_string(course_id) @@ -689,49 +693,6 @@ def load_single_xblock(request, user_id, course_id, usage_key_string, course=Non return instance -@csrf_exempt -def xqueue_callback(request, course_id, userid, mod_id, dispatch): - ''' - Entry point for graded results from the queueing system. - ''' - data = request.POST.copy() - - # Test xqueue package, which we expect to be: - # xpackage = {'xqueue_header': json.dumps({'lms_key':'secretkey',...}), - # 'xqueue_body' : 'Message from grader'} - for key in ['xqueue_header', 'xqueue_body']: - if key not in data: - raise Http404 - - header = json.loads(data['xqueue_header']) - if not isinstance(header, dict) or 'lms_key' not in header: - raise Http404 - - course_key = CourseKey.from_string(course_id) - - with modulestore().bulk_operations(course_key): - course = modulestore().get_course(course_key, depth=0) - - instance = load_single_xblock(request, userid, course_id, mod_id, course=course) - - # Transfer 'queuekey' from xqueue response header to the data. - # This is required to use the interface defined by 'handle_ajax' - data.update({'queuekey': header['lms_key']}) - - # We go through the "AJAX" path - # So far, the only dispatch from xqueue will be 'score_update' - try: - # Can ignore the return value--not used for xqueue_callback - instance.handle_ajax(dispatch, data) - # Save any state that has changed to the underlying KeyValueStore - instance.save() - except: - log.exception("error processing ajax call") - raise - - return HttpResponse("") - - @csrf_exempt @xframe_options_exempt @transaction.non_atomic_requests diff --git a/lms/djangoapps/courseware/tests/test_block_render.py b/lms/djangoapps/courseware/tests/test_block_render.py index 409b50a2164a..1d5ada5600a6 100644 --- a/lms/djangoapps/courseware/tests/test_block_render.py +++ b/lms/djangoapps/courseware/tests/test_block_render.py @@ -266,22 +266,6 @@ def setUp(self): self.mock_user.id = 1 self.request_factory = RequestFactoryNoCsrf() - # Construct a mock block for the modulestore to return - self.mock_block = MagicMock() - self.mock_block.id = 1 - self.dispatch = 'score_update' - - # Construct a 'standard' xqueue_callback url - self.callback_url = reverse( - 'xqueue_callback', - kwargs=dict( - course_id=str(self.course_key), - userid=str(self.mock_user.id), - mod_id=self.mock_block.id, - dispatch=self.dispatch - ) - ) - def tearDown(self): OverrideFieldData.provider_classes = None super().tearDown() @@ -317,63 +301,6 @@ def test_block_render_with_jump_to_id(self): # note if the URL mapping changes then this assertion will break assert '/courses/' + str(self.course_key) + '/jump_to_id/vertical_test' in html - def test_xqueue_callback_success(self): - """ - Test for happy-path xqueue_callback - """ - fake_key = 'fake key' - xqueue_header = json.dumps({'lms_key': fake_key}) - data = { - 'xqueue_header': xqueue_header, - 'xqueue_body': 'hello world', - } - - # Patch getmodule to return our mock block - with patch('lms.djangoapps.courseware.block_render.load_single_xblock', return_value=self.mock_block): - # call xqueue_callback with our mocked information - request = self.request_factory.post(self.callback_url, data) - render.xqueue_callback( - request, - str(self.course_key), - self.mock_user.id, - self.mock_block.id, - self.dispatch - ) - - # Verify that handle ajax is called with the correct data - request.POST._mutable = True # pylint: disable=protected-access - request.POST['queuekey'] = fake_key - self.mock_block.handle_ajax.assert_called_once_with(self.dispatch, request.POST) - - def test_xqueue_callback_missing_header_info(self): - data = { - 'xqueue_header': '{}', - 'xqueue_body': 'hello world', - } - - with patch('lms.djangoapps.courseware.block_render.load_single_xblock', return_value=self.mock_block): - # Test with missing xqueue data - with pytest.raises(Http404): # noqa: PT012 - request = self.request_factory.post(self.callback_url, {}) - render.xqueue_callback( - request, - str(self.course_key), - self.mock_user.id, - self.mock_block.id, - self.dispatch - ) - - # Test with missing xqueue_header - with pytest.raises(Http404): # noqa: PT012 - request = self.request_factory.post(self.callback_url, data) - render.xqueue_callback( - request, - str(self.course_key), - self.mock_user.id, - self.mock_block.id, - self.dispatch - ) - def _get_dispatch_url(self): """Helper to get dispatch URL for testing xblock callback.""" return reverse( @@ -609,21 +536,6 @@ def setUp(self): self.mock_user = UserFactory.create() self.request_factory = RequestFactoryNoCsrf() - # Construct a mock block for the modulestore to return - self.mock_block = MagicMock() - self.mock_block.id = 1 - self.dispatch = 'score_update' - - # Construct a 'standard' xqueue_callback url - self.callback_url = reverse( - 'xqueue_callback', kwargs={ - 'course_id': str(self.course_key), - 'userid': str(self.mock_user.id), - 'mod_id': self.mock_block.id, - 'dispatch': self.dispatch - } - ) - def _mock_file(self, name='file', size=10): """Create a mock file object for testing uploads""" mock_file = MagicMock( diff --git a/lms/djangoapps/courseware/tests/test_submitting_problems.py b/lms/djangoapps/courseware/tests/test_submitting_problems.py index 828c97609c39..9771897b4b7c 100644 --- a/lms/djangoapps/courseware/tests/test_submitting_problems.py +++ b/lms/djangoapps/courseware/tests/test_submitting_problems.py @@ -17,20 +17,21 @@ from django.contrib.auth.models import User # pylint: disable=imported-auth-user from django.db import connections from django.test import TestCase -from django.test.client import RequestFactory +from django.test.client import Client, RequestFactory from django.urls import reverse from django.utils.timezone import now from submissions import api as submissions_api +from submissions.models import ExternalGraderDetail from xblock_problem.capa.testing.response_xml_factory import ( CodeResponseXMLFactory, CustomResponseXMLFactory, OptionResponseXMLFactory, SchematicResponseXMLFactory, ) -from xblock_problem.capa.xqueue_interface import XQueueInterface from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.student.models import CourseEnrollment, anonymous_id_for_user +from common.djangoapps.student.tests.factories import UserFactory from lms.djangoapps.courseware.models import BaseStudentModuleHistory, StudentModule from lms.djangoapps.courseware.tests.helpers import LoginEnrollmentTestCase from lms.djangoapps.grades.api import CourseGradeFactory, task_compute_all_grades_for_course @@ -788,8 +789,7 @@ def problem_setup(self, name, files): # re-fetch the course from the database so the object is up to date self.refresh_course() - @patch.object(XQueueInterface, '_http_post') - def test_three_files(self, mock_xqueue_post): + def test_three_files(self): # Open the test files, and arrange to close them later. filenames = "prog1.py prog2.py prog3.py" fileobjs = [ @@ -800,19 +800,36 @@ def test_three_files(self, mock_xqueue_post): self.addCleanup(fileobj.close) self.problem_setup("the_problem", filenames) - mock_xqueue_post.return_value = (0, "ok") resp = self.submit_question_answer("the_problem", {'2_1': fileobjs}) assert resp.status_code == 200 json_resp = json.loads(resp.content.decode('utf-8')) assert json_resp['success'] == 'incorrect' - # See how post got called. - assert mock_xqueue_post.call_count == 1 - args, kwargs = mock_xqueue_post.call_args - assert len(args) == 2 - assert args[0].endswith('/submit/') - self.assertEqual(list(kwargs['files'].keys()), filenames.split()) # noqa: PT009 + # The submission and its files are waiting in edx-submissions for a grader. + external_grader = ExternalGraderDetail.objects.get() + assert external_grader.status == 'pending' + assert sorted(f.original_filename for f in external_grader.files.all()) == filenames.split() + + # A grader pulls the submission from the LMS and posts a result, as xqueue-watcher does. + grader = UserFactory(password="grader-password") + grader.groups.create(name="xqueue") + grader_client = Client() + grader_client.post("/xqueue/login/", {"username": grader.username, "password": "grader-password"}) + pulled = grader_client.get("/xqueue/get_submission/", {"queue_name": external_grader.queue_name}) + submission = json.loads(pulled.json()["content"]) + assert sorted(json.loads(submission["xqueue_files"])) == filenames.split() + grader_client.post("/xqueue/put_result/", { + "xqueue_header": submission["xqueue_header"], + "xqueue_body": json.dumps({"correct": True, "score": 1, "msg": "

    Good job

    "}), + }) + + # The learner's problem has the grader's result. + module = StudentModule.objects.get( + student=self.student_user, module_state_key=self.problem_location("the_problem") + ) + assert module.grade == 1.0 + assert json.loads(module.state)["correct_map"]["the_problem_2_1"]["correctness"] == "correct" class TestPythonGradedResponse(TestSubmittingProblems): diff --git a/lms/djangoapps/grades/signals/handlers.py b/lms/djangoapps/grades/signals/handlers.py index 7133d5434d24..5bf514932c43 100644 --- a/lms/djangoapps/grades/signals/handlers.py +++ b/lms/djangoapps/grades/signals/handlers.py @@ -420,7 +420,6 @@ def handle_external_grader_score(signal, sender, score, **kwargs): # pylint: disable=broad-exception-caught try: - # Use our new function instead of load_single_xblock # NOTE: Importing this at module level causes a circular import because # score_render → block_render → grades signals → back into this module. # Keeping it inside the handler avoids that by loading it only when needed. @@ -430,7 +429,7 @@ def handle_external_grader_score(signal, sender, score, **kwargs): usage_key, course=course) - # Call the handler method (mirroring the original xqueue_callback) + # Pass the grader's result to the problem's score_update handler instance.handle_ajax('score_update', data) # Save any state changes diff --git a/lms/envs/mock.yml b/lms/envs/mock.yml index 5a24cec063f7..db22f0ee6a4b 100644 --- a/lms/envs/mock.yml +++ b/lms/envs/mock.yml @@ -1196,14 +1196,6 @@ XBLOCK_SETTINGS: ScormXBlock: S3_BUCKET_NAME: scorm STORAGE_FUNC: openedxscorm.storage.s3 -XQUEUE_INTERFACE: - basic_auth: - - user - - pass - django_auth: - password: pass - username: user - url: http://localhost:18040 X_FRAME_OPTIONS: DENY YOUTUBE_API_KEY: test_youtube_api_key ZENDESK_API_KEY: '' diff --git a/lms/envs/test.py b/lms/envs/test.py index 392acc992302..617f0e5f55d9 100644 --- a/lms/envs/test.py +++ b/lms/envs/test.py @@ -66,14 +66,6 @@ USE_I18N = True LANGUAGE_CODE = 'en' # tests assume they will get English. -XQUEUE_INTERFACE = { - "url": "http://sandbox-xqueue.edx.org", - "django_auth": { - "username": "lms", - "password": "***REMOVED***" - }, - "basic_auth": ('anant', 'agarwal'), -} XQUEUE_WAITTIME_BETWEEN_REQUESTS = 5 # seconds # Don't rely on a real staff grading backend diff --git a/lms/urls.py b/lms/urls.py index 0e624d44981a..72e509569cb8 100644 --- a/lms/urls.py +++ b/lms/urls.py @@ -23,7 +23,6 @@ handle_xblock_callback, handle_xblock_callback_noauth, xblock_view, - xqueue_callback, ) from lms.djangoapps.courseware.masquerade import MasqueradeView from lms.djangoapps.courseware.views import views as courseware_views @@ -354,22 +353,6 @@ path('', include(('openedx.core.djangoapps.xblock.rest_api.urls', 'openedx.core.djangoapps.xblock'), namespace='xblock_api')), - re_path( - r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format( # noqa: UP032 - settings.COURSE_ID_PATTERN, - ), - xqueue_callback, - name='xqueue_callback', - ), - - re_path( - r'^courses/{}/xqueue/(?P[^/]*)/(?P.*?)/(?P[^/]*)$'.format( # noqa: UP032 - settings.COURSE_ID_PATTERN, - ), - xqueue_callback, - name='callback_submission', - ), - # TODO: These views need to be updated before they work path('calculate', util_views.calculate), diff --git a/openedx/core/djangoapps/xblock/runtime/shims.py b/openedx/core/djangoapps/xblock/runtime/shims.py index 8d1e22c64c01..72558daa6410 100644 --- a/openedx/core/djangoapps/xblock/runtime/shims.py +++ b/openedx/core/djangoapps/xblock/runtime/shims.py @@ -238,7 +238,6 @@ def xqueue(self): # TODO: Refactor capa to access this directly, don't bother the runtime. Then remove it from here. return { 'interface': None, - 'construct_callback': None, 'default_queuename': None, 'waittime': 5, # seconds; should come from settings.XQUEUE_WAITTIME_BETWEEN_REQUESTS } diff --git a/openedx/envs/common.py b/openedx/envs/common.py index 23f2d52d580e..d454df8b13ee 100644 --- a/openedx/envs/common.py +++ b/openedx/envs/common.py @@ -1463,16 +1463,8 @@ def add_optional_apps(optional_apps, installed_apps): ###################### CAPA External Code Evaluation ####################### -# Used with XQueue +# Seconds a learner must wait between submissions to a problem graded by an external grader. XQUEUE_WAITTIME_BETWEEN_REQUESTS = 5 # seconds -XQUEUE_INTERFACE = { - 'url': 'http://localhost:18040', - 'basic_auth': ['edx', 'edx'], - 'django_auth': { - 'username': 'lms', - 'password': 'password' - } -} ################################### CSRF ################################### diff --git a/openedx/envs/test.py b/openedx/envs/test.py index f683737e3fd1..6026d5157769 100644 --- a/openedx/envs/test.py +++ b/openedx/envs/test.py @@ -101,7 +101,6 @@ def make_staticfile_dirs(settings): # These ports are carefully chosen so that if the browser needs to # access them, they will be available through the SauceLabs SSH tunnel -XQUEUE_PORT = 8040 YOUTUBE_PORT = 8031 LTI_PORT = 8765 VIDEO_SOURCE_PORT = 8777 diff --git a/xmodule/services.py b/xmodule/services.py index 068cf2c9f39c..3ed117e126de 100644 --- a/xmodule/services.py +++ b/xmodule/services.py @@ -10,10 +10,8 @@ from config_models.models import ConfigurationModel from django.conf import settings -from django.urls import reverse from edx_when.field_data import DateLookupFieldData from eventtracking import tracker -from requests.auth import HTTPBasicAuth from xblock.reference.plugins import Service from xblock.runtime import KvsFieldData from xblock_problem.capa.xqueue_interface import XQueueInterface @@ -25,7 +23,6 @@ from lms.djangoapps.grades.api import signals as grades_signals from lms.djangoapps.lms_xblock.field_data import LmsFieldData from lms.djangoapps.lms_xblock.models import XBlockAsidesConfig -from openedx.core.djangoapps.waffle_utils import CourseWaffleFlag from xmodule.modulestore.django import modulestore if TYPE_CHECKING: @@ -316,22 +313,9 @@ def _handle_deprecated_progress_event(self, block, event): self.completion_service.submit_completion(block.scope_ids.usage_id, 1.0) -# .. toggle_name: send_to_submission_course.enable -# .. toggle_implementation: CourseWaffleFlag -# .. toggle_description: Enables use of the submissions service instead of legacy xqueue for course problem submissions. -# .. toggle_default: False -# .. toggle_use_cases: opt_in -# .. toggle_creation_date: 2024-04-03 -# .. toggle_expiration_date: 2025-08-12 -# .. toggle_will_remain_in_codebase: True -# .. toggle_tickets: none -# .. toggle_status: supported -SEND_TO_SUBMISSION_COURSE_FLAG = CourseWaffleFlag("send_to_submission_course.enable", __name__) - - class XQueueService: """ - XBlock service providing an interface to the XQueue service. + XBlock service that queues external grader submissions in edx-submissions. Args: block: The `ProblemBlock` instance. @@ -339,19 +323,7 @@ class XQueueService: def __init__(self, block: "ProblemBlock"): self._block = block - - basic_auth = settings.XQUEUE_INTERFACE.get("basic_auth") - requests_auth = HTTPBasicAuth(*basic_auth) if basic_auth else None - - use_submission = self.use_edx_submissions_for_xqueue() - - self._interface = XQueueInterface( - settings.XQUEUE_INTERFACE["url"], - settings.XQUEUE_INTERFACE["django_auth"], - requests_auth, - block=block, - use_submission_service=use_submission, - ) + self._interface = XQueueInterface(block) @property def interface(self): @@ -360,41 +332,6 @@ def interface(self): """ return self._interface - def use_edx_submissions_for_xqueue(self) -> bool: - """ - Determines whether edx-submissions should be used instead of legacy XQueue. - - This helper abstracts the toggle logic so that the rest of the codebase is not tied - to specific feature flag mechanics or rollout strategies. - - Returns: - bool: True if edx-submissions should be used, False otherwise. - """ - return SEND_TO_SUBMISSION_COURSE_FLAG.is_enabled(self._block.scope_ids.usage_id.context_key) - - def construct_callback(self, dispatch: str = "score_update") -> str: - """ - Return a fully qualified callback URL for the external queueing system. - """ - course_key = self._block.scope_ids.usage_id.context_key - userid = str(self._block.scope_ids.user_id) - mod_id = str(self._block.scope_ids.usage_id) - - callback_type = "xqueue_callback" - - relative_xqueue_callback_url = reverse( - callback_type, - kwargs={ - "course_id": str(course_key), - "userid": userid, - "mod_id": mod_id, - "dispatch": dispatch, - }, - ) - - xqueue_callback_url_prefix = settings.XQUEUE_INTERFACE.get("callback_url", settings.LMS_ROOT_URL) - return f"{xqueue_callback_url_prefix}{relative_xqueue_callback_url}" - @property def default_queuename(self) -> str: """ @@ -406,6 +343,6 @@ def default_queuename(self) -> str: @property def waittime(self) -> int: """ - Returns the number of seconds to wait in between calls to XQueue. + Returns the number of seconds a learner must wait between submissions to a queued problem. """ return settings.XQUEUE_WAITTIME_BETWEEN_REQUESTS diff --git a/xmodule/tests/test_capa_block.py b/xmodule/tests/test_capa_block.py index f5a26e800a93..c2179e20a4f0 100644 --- a/xmodule/tests/test_capa_block.py +++ b/xmodule/tests/test_capa_block.py @@ -14,7 +14,6 @@ import ddt import pytest -import requests import webob from codejail.safe_exec import SafeExecException from django.test import override_settings @@ -29,7 +28,7 @@ from xblock_problem.capa import responsetypes from xblock_problem.capa.correctmap import CorrectMap from xblock_problem.capa.responsetypes import LoncapaProblemError, ResponseError, StudentInputError -from xblock_problem.capa.xqueue_interface import XQueueInterface +from xblock_problem.capa.xqueue_submission import XQueueInterfaceSubmission from lms.djangoapps.courseware.user_state_client import XBlockUserState from openedx.core.djangolib.testing.utils import skip_unless_lms @@ -266,21 +265,6 @@ def test_showanswer_default(self): problem = CapaFactory.create() assert not problem.answer_available() - @ddt.data( - (requests.exceptions.ReadTimeout, (1, "failed to read from the server")), - (requests.exceptions.ConnectionError, (1, "cannot connect to server")), - ) - @ddt.unpack - def test_xqueue_request_exception(self, exception, result): - """ - Makes sure that platform will raise appropriate exception in case of - connect/read timeout(s) to request to xqueue - """ - xqueue_interface = XQueueInterface("http://example.com/xqueue", Mock()) - with patch.object(xqueue_interface.session, "post", side_effect=exception): - response = xqueue_interface._http_post("http://some/fake/url", {}) # pylint: disable=protected-access - assert response == result - def test_showanswer_attempted(self): """Check answer availability changes after attempting the problem.""" problem = CapaFactory.create(showanswer="attempted") @@ -1238,9 +1222,9 @@ def test_submit_problem_queued(self): assert block.attempts == 1 @pytest.mark.django_db - @patch.object(XQueueInterface, "_http_post") + @patch.object(XQueueInterfaceSubmission, "send_to_submission") def test_submit_problem_with_files(self, mock_xqueue_post): - """Verify file-upload submissions are sent correctly to XQueue via submit_problem.""" + """Verify file-upload submissions reach edx-submissions via submit_problem.""" # Check a problem with uploaded files, using the submit_problem API. # The files we'll be uploading. @@ -1252,8 +1236,8 @@ def test_submit_problem_with_files(self, mock_xqueue_post): block = CapaFactoryWithFiles.create() - # Mock the XQueueInterface post method - mock_xqueue_post.return_value = (0, "ok") + # Mock the hand-off to edx-submissions + mock_xqueue_post.return_value = {} # Create a request dictionary for submit_problem. get_request_dict = { @@ -1263,51 +1247,24 @@ def test_submit_problem_with_files(self, mock_xqueue_post): block.submit_problem(get_request_dict) - # _http_post is called like this: - # _http_post( - # 'http://example.com/xqueue/xqueue/submit/', - # { - # 'xqueue_header': - # '{"lms_key": "df34fb702620d7ae892866ba57572491", ' - # '"lms_callback_url": "/", ' - # '"queue_name": "BerkeleyX-cs188x"}', - # 'xqueue_body': - # '{"student_info": "{\\"anonymous_student_id\\": ' - # '\\"student\\", \\"submission_time\\": ' - # '\\"20131117183318\\"}", ' - # '"grader_payload": "{\\"project\\": \\"p3\\"}", ' - # '"student_response": ""}', - # }, - # files={ - # path( - # u'/home/ned/edx/edx-platform/common/test/data/uploads/' - # 'asset.html' - # ): - # , - # path( - # u'/home/ned/edx/edx-platform/common/test/data/uploads/' - # 'image.jpg' - # ): - # , - # path( - # u'/home/ned/edx/edx-platform/common/test/data/uploads/' - # 'textbook.pdf' - # ): - # , - # }, + # send_to_submission is called like this: + # send_to_submission( + # '{"lms_key": "df34fb702620d7ae892866ba57572491", "queue_name": "BerkeleyX-cs188x"}', + # '{"student_info": "{\\"anonymous_student_id\\": \\"student\\", ' + # '\\"submission_time\\": \\"20131117183318\\"}", ' + # '"grader_payload": "{\\"project\\": \\"p3\\"}", "student_response": ""}', + # "df34fb702620d7ae892866ba57572491", + # {"/path/to/prog1.py": , ...}, # ) assert mock_xqueue_post.call_count == 1 - _, kwargs = mock_xqueue_post.call_args - self.assertCountEqual(fpaths, list(kwargs["files"].keys())) # noqa: PT009 - for fpath, fileobj in kwargs["files"].items(): + files = mock_xqueue_post.call_args.args[3] + self.assertCountEqual(fpaths, list(files.keys())) # noqa: PT009 + for fpath, fileobj in files.items(): assert fpath == fileobj.name @pytest.mark.django_db - @patch.object(XQueueInterface, "_http_post") + @patch.object(XQueueInterfaceSubmission, "send_to_submission") def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post): """Verify file-upload submissions work correctly via the XBlock handler API.""" # Check a problem with uploaded files, using the XBlock API. @@ -1322,8 +1279,8 @@ def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post): block = CapaFactoryWithFiles.create() - # Mock the XQueueInterface post method - mock_xqueue_post.return_value = (0, "ok") + # Mock the hand-off to edx-submissions + mock_xqueue_post.return_value = {} # Create a webob Request with the files uploaded. post_data = [] @@ -1335,9 +1292,9 @@ def test_submit_problem_with_files_as_xblock(self, mock_xqueue_post): block.handle("xmodule_handler", request, "problem_check") assert mock_xqueue_post.call_count == 1 - _, kwargs = mock_xqueue_post.call_args - self.assertCountEqual(fnames, list(kwargs["files"].keys())) # noqa: PT009 - for fpath, fileobj in kwargs["files"].items(): + files = mock_xqueue_post.call_args.args[3] + self.assertCountEqual(fnames, list(files.keys())) # noqa: PT009 + for fpath, fileobj in files.items(): assert fpath == fileobj.name def test_submit_problem_error(self): @@ -3976,7 +3933,7 @@ def test_rerandomized_inputs(self): } @pytest.mark.django_db - @patch.object(XQueueInterface, "_http_post") + @patch.object(XQueueInterfaceSubmission, "send_to_submission") def test_file_inputs(self, mock_xqueue_post): """Verify tracking data for file submission and custom response inputs.""" fnames = ["prog1.py", "prog2.py", "prog3.py"] @@ -3989,8 +3946,8 @@ def test_file_inputs(self, mock_xqueue_post): factory = CapaFactoryWithFiles block = factory.create() - # Mock the XQueueInterface post method - mock_xqueue_post.return_value = (0, "ok") + # Mock the hand-off to edx-submissions + mock_xqueue_post.return_value = {} answer_input_dict = { CapaFactoryWithFiles.input_key(response_num=2): fileobjs, diff --git a/xmodule/tests/test_services.py b/xmodule/tests/test_services.py index 4015cbd45b4d..19e77d03ad56 100644 --- a/xmodule/tests/test_services.py +++ b/xmodule/tests/test_services.py @@ -3,7 +3,7 @@ """ import unittest from unittest import TestCase, mock -from unittest.mock import Mock, patch +from unittest.mock import Mock import ddt import pytest @@ -184,44 +184,9 @@ def setUp(self): self.service = XQueueService(self.block) def test_interface(self): - """Test that the `XQUEUE_INTERFACE` settings are passed from the service to the interface.""" + """The service wraps an XQueueInterface for the block.""" assert isinstance(self.service.interface, XQueueInterface) - assert self.service.interface.url == "http://sandbox-xqueue.edx.org" - assert self.service.interface.auth["username"] == "lms" - assert self.service.interface.auth["password"] == "***REMOVED***" - assert self.service.interface.session.auth.username == "anant" - assert self.service.interface.session.auth.password == "agarwal" - - @patch("xmodule.services.XQueueService.use_edx_submissions_for_xqueue", return_value=True) - def test_construct_callback_with_flag_enabled(self, mock_flag): # pylint: disable=unused-argument - """Test construct_callback when the waffle flag is enabled.""" - self.service = XQueueService(self.block) - usage_id = self.block.scope_ids.usage_id - course_id = str(usage_id.course_key) - callback_url = f"courses/{course_id}/xqueue/user1/{usage_id}" - - assert self.service.construct_callback() == f"{settings.LMS_ROOT_URL}/{callback_url}/score_update" - assert self.service.construct_callback("alt_dispatch") == ( - f"{settings.LMS_ROOT_URL}/{callback_url}/alt_dispatch" - ) - - custom_callback_url = "http://alt.url" - with override_settings(XQUEUE_INTERFACE={**settings.XQUEUE_INTERFACE, "callback_url": custom_callback_url}): - assert self.service.construct_callback() == f"{custom_callback_url}/{callback_url}/score_update" - - @patch("xmodule.services.XQueueService.use_edx_submissions_for_xqueue", return_value=False) - def test_construct_callback_with_flag_disabled(self, mock_flag): # pylint: disable=unused-argument - """Test construct_callback when the waffle flag is disabled.""" - self.service = XQueueService(self.block) - usage_id = self.block.scope_ids.usage_id - callback_url = f"courses/{usage_id.context_key}/xqueue/user1/{usage_id}" - - assert self.service.construct_callback() == f"{settings.LMS_ROOT_URL}/{callback_url}/score_update" - assert self.service.construct_callback("alt_dispatch") == f"{settings.LMS_ROOT_URL}/{callback_url}/alt_dispatch" - - custom_callback_url = "http://alt.url" - with override_settings(XQUEUE_INTERFACE={**settings.XQUEUE_INTERFACE, "callback_url": custom_callback_url}): - assert self.service.construct_callback() == f"{custom_callback_url}/{callback_url}/score_update" + assert self.service.interface.block is self.block def test_default_queuename(self): """Check the format of the default queue name.""" From 373d8dec0b4199e5f1065f69d34783a4683c2c3b Mon Sep 17 00:00:00 2001 From: Feanil Patel Date: Tue, 24 Nov 2026 09:57:21 -0500 Subject: [PATCH 3/4] feat!: upgrade xblocks-core to 4.0.0 4.0.0 removes the legacy XQueue HTTP path and the MATLAB integration (https://github.com/openedx/xblocks-core/pull/338), which the two commits before this one adapt the platform to. XQueueInterface now takes only the block, LoncapaSystem no longer accepts matlab_api_key, and problems refuse new submissions instead of queueing them. Release notes: https://github.com/openedx/xblocks-core/releases/tag/v4.0.0 BREAKING CHANGE: MATLAB problems can no longer be submitted. They still load and keep their scores. Co-Authored-By: Claude Opus 5.5 --- requirements/edx/base.txt | 2 +- requirements/edx/development.txt | 2 +- uv.lock | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/requirements/edx/base.txt b/requirements/edx/base.txt index e948b85fdac5..2ecc2327eb2e 100644 --- a/requirements/edx/base.txt +++ b/requirements/edx/base.txt @@ -1322,7 +1322,7 @@ xblock==6.3.5 xblock-drag-and-drop-v2==5.1.2 xblock-google-drive==0.8.2 xblock-poll==1.16.1 -xblocks-core==3.0.0 +xblocks-core==4.0.0 xmlsec==1.3.14 # via python3-saml xss-utils==1.1.0 diff --git a/requirements/edx/development.txt b/requirements/edx/development.txt index 3ffe864ea7cc..19bfdb0bfe37 100644 --- a/requirements/edx/development.txt +++ b/requirements/edx/development.txt @@ -1604,7 +1604,7 @@ xblock==6.3.5 xblock-drag-and-drop-v2==5.1.2 xblock-google-drive==0.8.2 xblock-poll==1.16.1 -xblocks-core==3.0.0 +xblocks-core==4.0.0 xmlsec==1.3.14 # via python3-saml xss-utils==1.1.0 diff --git a/uv.lock b/uv.lock index 25575e27c389..55cb7b1c9bd4 100644 --- a/uv.lock +++ b/uv.lock @@ -8248,7 +8248,7 @@ wheels = [ [[package]] name = "xblocks-core" -version = "3.0.0" +version = "4.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "beautifulsoup4" }, @@ -8280,9 +8280,9 @@ dependencies = [ { name = "wrapt" }, { name = "xblock" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/5c/6c/ff9e81dd4d0b448eed086f677553fde801ac68e6961bee95852a81e361af/xblocks_core-3.0.0.tar.gz", hash = "sha256:bf0d17ae9b251001c9f1c56e6583f7664707f7e8e7c8576796d7b9b399ec05fc", size = 3967738, upload-time = "2026-11-18T15:53:42.119Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f7/f9/9aebe07dd9d0b716840e9bdaecd5b5c685e1e590f74abd8741f3ee1beb2d/xblocks_core-4.0.0.tar.gz", hash = "sha256:13ca82047b2d48517ea9b36c4407a9a927988f35bd5e445fc276d36327a2e121", size = 3956202, upload-time = "2026-11-24T13:52:48.111Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/21/17/6d1c4d51b930e4d02344633e7cf87300a7e329b7dd0769c41c47aab74f92/xblocks_core-3.0.0-py3-none-any.whl", hash = "sha256:c9b0a8f60084fcb0899d962eb558a6117ffb934c0d97ed61622f7c6ee89b3361", size = 3754524, upload-time = "2026-11-18T15:53:40.55Z" }, + { url = "https://files.pythonhosted.org/packages/b2/2c/2a56a4580db7fede53c52adb3aaf113e33557b2cea73ce31114e1afa09c9/xblocks_core-4.0.0-py3-none-any.whl", hash = "sha256:8a1ac3a128ce7e6ef9af75e69d2c31b05f246cf6efd5b7031faf3086d4eca984", size = 3749437, upload-time = "2026-11-24T13:52:46.47Z" }, ] [[package]] From 7a2164ff6ebe11832aa76dfa92346a4bdfa9c363 Mon Sep 17 00:00:00 2001 From: Feanil Patel Date: Tue, 24 Nov 2026 10:31:33 -0500 Subject: [PATCH 4/4] test: ignore the LTI block's i18n_service in the preview handler test xblocks-core 3.1.0 started passing i18n_service to render_django_template in LTIBlock.preview_handler (https://github.com/openedx/xblocks-core/pull/336), so the mocked render output no longer matches the expected template call. Strip it the same way test_lti_constructor already does for student_view. Co-Authored-By: Claude Opus 5.5 --- lms/djangoapps/courseware/tests/test_lti_integration.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lms/djangoapps/courseware/tests/test_lti_integration.py b/lms/djangoapps/courseware/tests/test_lti_integration.py index 11d2c3a6b0ad..688afbc8c5a6 100644 --- a/lms/djangoapps/courseware/tests/test_lti_integration.py +++ b/lms/djangoapps/courseware/tests/test_lti_integration.py @@ -149,14 +149,16 @@ def test_lti_constructor(self, mock_render_django_template): @patch('xblock.utils.resources.ResourceLoader.render_django_template', side_effect=mock_render_template) def test_lti_preview_handler(self, mock_render_django_template): - generated_content = self.block.preview_handler(None, None).body + generated_content = self.block.preview_handler(None, None).body.decode('utf-8') if settings.USE_EXTRACTED_LTI_BLOCK: + # Remove i18n service from the extracted LTI Block's rendered `preview_handler` content + generated_content = re.sub(r"\{.*?}", "{}", generated_content) expected_content = self.runtime.render_template('templates/lti_form.html', self.expected_context) mock_render_django_template.assert_called_once() else: expected_content = self.runtime.render_template('lti_form.html', self.expected_context) - assert generated_content.decode('utf-8') == expected_content + assert generated_content == expected_content class _TestLTIBlockListingBase(SharedModuleStoreTestCase):