diff --git a/src/xblock_problem/assets/fixtures/matlabinput_problem.html b/src/xblock_problem/assets/fixtures/queued_codeinput_problem.html
similarity index 56%
rename from src/xblock_problem/assets/fixtures/matlabinput_problem.html
rename to src/xblock_problem/assets/fixtures/queued_codeinput_problem.html
index 93e06ffe..22dd5d3f 100644
--- a/src/xblock_problem/assets/fixtures/matlabinput_problem.html
+++ b/src/xblock_problem/assets/fixtures/queued_codeinput_problem.html
@@ -1,35 +1,27 @@
-
-
-
+
diff --git a/src/xblock_problem/assets/spec/display_spec.js b/src/xblock_problem/assets/spec/display_spec.js
index 7410e1e7..3a1298d7 100644
--- a/src/xblock_problem/assets/spec/display_spec.js
+++ b/src/xblock_problem/assets/spec/display_spec.js
@@ -1141,15 +1141,15 @@ data-url='/problem/quiz/'> \
});
});
- describe("Submitting an xqueue-graded problem", function () {
- const matlabinput_html = readFixtures("matlabinput_problem.html");
+ describe("Submitting an externally graded problem", function () {
+ const queued_problem_html = readFixtures("queued_codeinput_problem.html");
beforeEach(function () {
- spyOn($, "postWithPrefix").and.callFake((url, callback) => callback({ html: matlabinput_html }));
+ spyOn($, "postWithPrefix").and.callFake((url, callback) => callback({ html: queued_problem_html }));
jasmine.clock().install();
this.problem = new Problem(mockRuntime, $(".xblock-student_view"));
spyOn(this.problem, "poll").and.callThrough();
- this.problem.render(matlabinput_html);
+ this.problem.render(queued_problem_html);
});
afterEach(() => jasmine.clock().uninstall());
diff --git a/src/xblock_problem/block.py b/src/xblock_problem/block.py
index bc209116..2b8a2fd2 100644
--- a/src/xblock_problem/block.py
+++ b/src/xblock_problem/block.py
@@ -387,17 +387,6 @@ class ProblemBlock(ScorableXBlockMixin, LegacyXmlMixin, XBlock):
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,
@@ -492,7 +481,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
@@ -619,10 +607,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
@@ -716,7 +700,6 @@ def max_score(self):
resources_fs=self.runtime.resources_fs,
seed=None,
xqueue=None,
- matlab_api_key=None,
)
try:
lcp = LoncapaProblem(
@@ -764,7 +747,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,
@@ -777,7 +760,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
@@ -940,7 +922,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(
@@ -1624,29 +1605,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/src/xblock_problem/capa/capa_problem.py b/src/xblock_problem/capa/capa_problem.py
index 5882bdd4..0e069af0 100644
--- a/src/xblock_problem/capa/capa_problem.py
+++ b/src/xblock_problem/capa/capa_problem.py
@@ -105,7 +105,6 @@ def __init__( # pylint: disable=too-many-positional-arguments,too-many-argument
resources_fs,
seed, # Why do we do this if we have self.seed?
xqueue,
- matlab_api_key=None,
):
self.ajax_url = ajax_url
self.anonymous_student_id = anonymous_student_id
@@ -119,7 +118,6 @@ def __init__( # pylint: disable=too-many-positional-arguments,too-many-argument
self.seed = seed # Why do we do this if we have self.seed?
self.STATIC_URL = settings.STATIC_URL # pylint: disable=invalid-name
self.xqueue = xqueue
- self.matlab_api_key = matlab_api_key
class LoncapaProblem:
@@ -409,19 +407,6 @@ def update_score(self, score_msg, queuekey):
self.correct_map.set_dict(cmap.get_dict())
return cmap
- def ungraded_response(self, xqueue_msg, queuekey):
- """
- Handle any responses from the xqueue that do not contain grades
- Will try to pass the queue message to all inputtypes that can handle ungraded responses
-
- Does not return any value
- """
- # check against each inputtype
- for the_input in self.inputs.values():
- # if the input type has an ungraded function, pass in the values
- if hasattr(the_input, "ungraded_response"):
- the_input.ungraded_response(xqueue_msg, queuekey)
-
def is_queued(self):
"""
Returns True if any part of the problem has been submitted to an external queue
diff --git a/src/xblock_problem/capa/inputtypes.py b/src/xblock_problem/capa/inputtypes.py
index 348fdf4c..5fd62e8c 100644
--- a/src/xblock_problem/capa/inputtypes.py
+++ b/src/xblock_problem/capa/inputtypes.py
@@ -44,8 +44,6 @@
import re
import shlex # for splitting quoted strings
import sys
-import time
-from datetime import datetime
import html5lib
import nh3
@@ -55,13 +53,10 @@
from chem import chemcalc
from lxml import etree
-from xblock_problem.capa.xqueue_interface import XQUEUE_TIMEOUT
from xblock_problem.markup import HTML, Text
from xblock_problem.stringify import stringify_children
-from . import xqueue_interface
from .registry import TagRegistry
-from .util import sanitize_html
log = logging.getLogger(__name__)
@@ -755,9 +750,15 @@ class CodeInput(InputTypeBase):
template = "codeinput.html"
tags = [
"codeinput",
- "textbox",
# Another (older) name--at some point we may want to make it use a
# non-codemirror editor.
+ "textbox",
+ # MATLAB problems used a MatlabInput subclass that sent code to the
+ # MathWorks service through XQueue. That integration is gone
+ # (https://github.com/openedx/public-engineering/issues/192); the tag
+ # stays so old problems still parse and keep their scores. CodeResponse
+ # refuses new submissions on it.
+ "matlabinput",
]
@classmethod
@@ -822,207 +823,6 @@ def _extra_context(self):
# -----------------------------------------------------------------------------
-@registry.register
-class MatlabInput(CodeInput):
- """
- InputType for handling Matlab code input
-
- Example::
-
-
- Initial Text
-
-
- """
-
- template = "matlabinput.html"
- tags = ["matlabinput"]
-
- def setup(self):
- """
- Handle matlab-specific parsing
- """
- _ = self.capa_system.i18n.gettext
-
- submitted_msg = _(
- "Submitted. As soon as a response is returned, this message will be replaced by that feedback."
- )
- self.submitted_msg = submitted_msg
-
- self.setup_code_response_rendering()
-
- xml = self.xml
-
- self.plot_payload = xml.findtext("./plot_payload")
- # Check if problem has been queued
- self.queuename = "matlab"
- self.queue_msg = ""
- # this is only set if we don't have a graded response
- # the graded response takes precedence
- if "queue_msg" in self.input_state and self.status in ["queued", "incomplete", "unsubmitted"]:
- self.queue_msg = sanitize_html(self.input_state["queue_msg"])
-
- if "queuestate" in self.input_state and self.input_state["queuestate"] == "queued":
- self.status = "queued"
- self.queue_len = 1
- self.msg = self.submitted_msg
- # Handle situation if no response from xqueue arrived during specified time.
- if "queuetime" not in self.input_state or time.time() - self.input_state["queuetime"] > XQUEUE_TIMEOUT:
- self.queue_len = 0
- self.status = "unsubmitted"
- self.msg = _("No response from Xqueue within {xqueue_timeout} seconds. Aborted.").format(
- xqueue_timeout=XQUEUE_TIMEOUT
- )
-
- def handle_ajax(self, dispatch, data):
- """
- Handle AJAX calls directed to this input
-
- Args:
- - dispatch (str) - indicates how we want this ajax call to be handled
- - data (dict) - dictionary of key-value pairs that contain useful data
- Returns:
- dict - 'success' - whether or not we successfully queued this submission
- - 'message' - message to be rendered in case of error
- """
-
- if dispatch == "plot":
- return self._plot_data(data)
- return {}
-
- def ungraded_response(self, queue_msg, queuekey):
- """
- Handle the response from the XQueue
- Stores the response in the input_state so it can be rendered later
-
- Args:
- - queue_msg (str) - message returned from the queue. The message to be rendered
- - queuekey (str) - a key passed to the queue. Will be matched up to verify that
- this is the response we're waiting for
-
- Returns:
- nothing
- """
- # check the queuekey against the saved queuekey
- if (
- "queuestate" in self.input_state
- and self.input_state["queuestate"] == "queued"
- and self.input_state["queuekey"] == queuekey
- ):
- msg = self._parse_data(queue_msg)
- # save the queue message so that it can be rendered later
- self.input_state["queue_msg"] = msg
- self.input_state["queuestate"] = None
- self.input_state["queuekey"] = None
-
- def button_enabled(self):
- """Return whether or not we want the 'Test Code' button visible
-
- Right now, we only want this button to show up when a problem has not been
- checked.
- """
- if self.status in ["correct", "incorrect", "partially-correct"]:
- return False
-
- return True
-
- def _extra_context(self):
- """Set up additional context variables"""
-
- _ = self.capa_system.i18n.gettext
-
- queue_msg = self.queue_msg
- if len(self.queue_msg) > 0: # An empty string cannot be parsed as XML but is okay to include in the template.
- try:
- etree.XML(HTML("
{0}
").format(HTML(self.queue_msg)))
- except etree.XMLSyntaxError:
- try:
- html5lib.parseFragment(self.queue_msg, treebuilder="lxml", namespaceHTMLElements=False)[0]
- except (IndexError, ValueError):
- # If neither can parse queue_msg, it contains invalid xml.
- queue_msg = HTML("{0}").format(_("Error running code."))
-
- extra_context = {
- "queue_len": str(self.queue_len),
- "queue_msg": queue_msg,
- "button_enabled": self.button_enabled(),
- "matlab_editor_js": f"{self.capa_system.STATIC_URL}js/vendor/CodeMirror/octave.js",
- "msg": sanitize_html(self.msg), # sanitize msg before rendering into template
- # Translated here, not in the template's inline JS, so it comes from the block's catalog.
- "still_running_msg": _("Your code is still being run. Refresh the page to see updates."),
- }
- return extra_context
-
- def _parse_data(self, queue_msg):
- """
- Parses the message out of the queue message
- Args:
- queue_msg (str) - a JSON encoded string
- Returns:
- returns the value for the the key 'msg' in queue_msg
- """
- try:
- result = json.loads(queue_msg)
- except (TypeError, ValueError):
- log.error("External message should be a JSON serialized dict. Received queue_msg = %s", queue_msg)
- raise
- msg = result["msg"]
- return msg
-
- def _plot_data(self, data):
- """
- AJAX handler for the plot button
- Args:
- get (dict) - should have key 'submission' which contains the student submission
- Returns:
- dict - 'success' - whether or not we successfully queued this submission
- - 'message' - message to be rendered in case of error
- """
- _ = self.capa_system.i18n.gettext
- # only send data if xqueue exists
- if self.capa_system.xqueue is None:
- return {"success": False, "message": _("Cannot connect to the queue")}
-
- # pull relevant info out of get
- response = data["submission"]
-
- # construct xqueue headers
- qinterface = self.capa_system.xqueue.interface
- qtime = datetime.utcnow().strftime(xqueue_interface.DATEFORMAT)
- callback_url = self.capa_system.xqueue.construct_callback("ungraded_response")
- anonymous_student_id = self.capa_system.anonymous_student_id
- # TODO: Why is this using self.capa_system.seed when we have self.seed???
- queuekey = xqueue_interface.make_hashkey(
- str(self.capa_system.seed) + qtime + anonymous_student_id + self.input_id
- )
- xheader = xqueue_interface.make_xheader(
- lms_callback_url=callback_url, lms_key=queuekey, queue_name=self.queuename
- )
-
- # construct xqueue body
- student_info = {"anonymous_student_id": anonymous_student_id, "submission_time": qtime}
- contents = {
- "grader_payload": self.plot_payload,
- "student_info": json.dumps(student_info),
- "student_response": response,
- "token": getattr(self.capa_system, "matlab_api_key", None),
- "endpoint_version": "2",
- "requestor_id": anonymous_student_id,
- }
-
- error, msg = qinterface.send_to_queue(header=xheader, body=json.dumps(contents))
- # save the input state if successful
- if error == 0:
- self.input_state["queuekey"] = queuekey
- self.input_state["queuestate"] = "queued"
- self.input_state["queuetime"] = time.time()
-
- return {"success": error == 0, "message": msg}
-
-
-# -----------------------------------------------------------------------------
-
-
@registry.register
class Schematic(InputTypeBase):
"""
diff --git a/src/xblock_problem/capa/responsetypes.py b/src/xblock_problem/capa/responsetypes.py
index 2cbf1177..3f1d1c79 100644
--- a/src/xblock_problem/capa/responsetypes.py
+++ b/src/xblock_problem/capa/responsetypes.py
@@ -2579,17 +2579,14 @@ def execute_check_function(self, idset, submission):
@registry.register
class CodeResponse(LoncapaResponse):
"""
- Grade student code using an external queueing server, called 'xqueue'.
+ Grade student code with an external grader that pulls submissions from the LMS.
- Expects 'xqueue' dict in LoncapaSystem with the following properties that are
+ Expects 'xqueue' object in LoncapaSystem with the following properties that are
needed by CodeResponse::
capa_system.xqueue = object with properties:
interface: XQueueInterface object.
- construct_callback: Per-StudentModule callback URL constructor,
- defaults to using 'score_update' as the correct dispatch (function).
default_queuename: Default queue name to submit request (string).
- }
External requests are only submitted for student submission grading, not
for getting reference answers.
@@ -2643,18 +2640,11 @@ def _parse_coderesponse_xml(self, codeparam):
"grader_payload": grader_payload,
}
- # matlab api key can be defined in course settings. if so, add it to the grader payload
- api_key = getattr(self.capa_system, "matlab_api_key", None)
- if api_key and self.xml.find("matlabinput") is not None:
- self.payload["token"] = api_key
- self.payload["endpoint_version"] = "2"
- self.payload["requestor_id"] = self.capa_system.anonymous_student_id
-
self.initial_display = find_with_default(codeparam, "initial_display", "")
_ = self.capa_system.i18n.gettext
self.answer = find_with_default(codeparam, "answer_display", _("No answer provided."))
- def get_score(self, student_answers): # pylint: disable=too-many-locals
+ def get_score(self, student_answers):
_ = self.capa_system.i18n.gettext
try:
# Note that submission can be a file
@@ -2668,6 +2658,14 @@ def get_score(self, student_answers): # pylint: disable=too-many-locals
)
raise Exception(err) from err # pylint: disable=broad-exception-raised
+ # MATLAB problems sent code to the MathWorks service through XQueue, and neither
+ # exists any more (https://github.com/openedx/public-engineering/issues/192). The
+ # tag stays so old problems parse and keep their scores, but a new submission has
+ # no grader to go to, so tell the learner instead of queueing it. Raising keeps
+ # the attempt from being counted.
+ if self.inputfields[0].tag == "matlabinput":
+ raise ResponseError(_("MATLAB problems can no longer be graded."))
+
# We do not support xqueue within Studio.
if self.capa_system.xqueue is None:
cmap = CorrectMap()
@@ -2684,8 +2682,7 @@ def get_score(self, student_answers): # pylint: disable=too-many-locals
# Generate header
queuekey = make_hashkey(str(self.capa_system.seed) + qtime + anonymous_student_id + self.answer_id)
- callback_url = self.capa_system.xqueue.construct_callback()
- xheader = make_xheader(lms_callback_url=callback_url, lms_key=queuekey, queue_name=self.queue_name)
+ xheader = make_xheader(lms_key=queuekey, queue_name=self.queue_name)
# Generate body
if is_list_of_files(submission):
@@ -2722,22 +2719,32 @@ def get_score(self, student_answers): # pylint: disable=too-many-locals
"time": qtime,
}
- cmap = CorrectMap()
if error:
+ # Raising here, rather than returning an error correct map, keeps the failed
+ # hand-off from counting as an attempt: submit_problem catches ResponseError and
+ # shows the message without counting the attempt or replacing the correct map.
+ # It does save the new answers, so two cases are left behind on purpose, since
+ # this is a failure path and the first is what every ResponseError already does:
+ # - If an earlier submission is still queued, the failed answer is saved next
+ # to that submission's queue state, and its grade lands beside the new answer.
+ # - In a problem with more than one , a response queued before
+ # this one failed stays pending in edx-submissions, and update_score ignores
+ # the grader's reply since its queue key never made it into the correct map.
_ = self.capa_system.i18n.gettext
- error_msg = _(
- "Unable to deliver your submission to grader (Reason: {error_msg}). Please try again later."
- ).format(error_msg=msg)
- cmap.set(self.answer_id, queuestate=None, msg=error_msg)
- else:
- # Queueing mechanism flags:
- # 1) Backend: Non-null CorrectMap['queuestate'] indicates that
- # the problem has been queued
- # 2) Frontend: correctness='incomplete' eventually trickles down
- # through inputtypes.textbox and .filesubmission to inform the
- # browser to poll the LMS
- cmap.set(self.answer_id, queuestate=queuestate, correctness="incomplete", msg=msg)
+ raise ResponseError(
+ _("Unable to deliver your submission to grader (Reason: {error_msg}). Please try again later.").format(
+ error_msg=msg
+ )
+ )
+ # Queueing mechanism flags:
+ # 1) Backend: Non-null CorrectMap['queuestate'] indicates that
+ # the problem has been queued
+ # 2) Frontend: correctness='incomplete' eventually trickles down
+ # through inputtypes.textbox and .filesubmission to inform the
+ # browser to poll the LMS
+ cmap = CorrectMap()
+ cmap.set(self.answer_id, queuestate=queuestate, correctness="incomplete", msg=msg)
return cmap
def update_score(self, score_msg, oldcmap, queuekey):
diff --git a/src/xblock_problem/capa/static/js/vendor/CodeMirror/octave.js b/src/xblock_problem/capa/static/js/vendor/CodeMirror/octave.js
deleted file mode 100644
index 23cd2fe2..00000000
--- a/src/xblock_problem/capa/static/js/vendor/CodeMirror/octave.js
+++ /dev/null
@@ -1,118 +0,0 @@
-CodeMirror.defineMode("octave", function() {
- function wordRegexp(words) {
- return new RegExp("^((" + words.join(")|(") + "))\\b");
- }
-
- var singleOperators = new RegExp("^[\\+\\-\\*/&|\\^~<>!@'\\\\]");
- var singleDelimiters = new RegExp('^[\\(\\[\\{\\},:=;]');
- var doubleOperators = new RegExp("^((==)|(~=)|(<=)|(>=)|(<<)|(>>)|(\\.[\\+\\-\\*/\\^\\\\]))");
- var doubleDelimiters = new RegExp("^((!=)|(\\+=)|(\\-=)|(\\*=)|(/=)|(&=)|(\\|=)|(\\^=))");
- var tripleDelimiters = new RegExp("^((>>=)|(<<=))");
- var expressionEnd = new RegExp("^[\\]\\)]");
- var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
-
- var builtins = wordRegexp([
- 'error', 'eval', 'function', 'abs', 'acos', 'atan', 'asin', 'cos',
- 'cosh', 'exp', 'log', 'prod', 'log10', 'max', 'min', 'sign', 'sin', 'sinh',
- 'sqrt', 'tan', 'reshape', 'break', 'zeros', 'default', 'margin', 'round', 'ones',
- 'rand', 'syn', 'ceil', 'floor', 'size', 'clear', 'zeros', 'eye', 'mean', 'std', 'cov',
- 'det', 'eig', 'inv', 'norm', 'rank', 'trace', 'expm', 'logm', 'sqrtm', 'linspace', 'plot',
- 'title', 'xlabel', 'ylabel', 'legend', 'text', 'meshgrid', 'mesh', 'num2str'
- ]);
-
- var keywords = wordRegexp([
- 'return', 'case', 'switch', 'else', 'elseif', 'end', 'endif', 'endfunction',
- 'if', 'otherwise', 'do', 'for', 'while', 'try', 'catch', 'classdef', 'properties', 'events',
- 'methods', 'global', 'persistent', 'endfor', 'endwhile', 'printf', 'disp', 'until', 'continue'
- ]);
-
-
- // tokenizers
- function tokenTranspose(stream, state) {
- if (!stream.sol() && stream.peek() === '\'') {
- stream.next();
- state.tokenize = tokenBase;
- return 'operator';
- }
- state.tokenize = tokenBase;
- return tokenBase(stream, state);
- }
-
-
- function tokenComment(stream, state) {
- if (stream.match(/^.*%}/)) {
- state.tokenize = tokenBase;
- return 'comment';
- };
- stream.skipToEnd();
- return 'comment';
- }
-
- function tokenBase(stream, state) {
- // whitespaces
- if (stream.eatSpace()) return null;
-
- // Handle one line Comments
- if (stream.match('%{')){
- state.tokenize = tokenComment;
- stream.skipToEnd();
- return 'comment';
- }
-
- if (stream.match(/^(%)|(\.\.\.)/)){
- stream.skipToEnd();
- return 'comment';
- }
-
- // Handle Number Literals
- if (stream.match(/^[0-9\.+-]/, false)) {
- if (stream.match(/^[+-]?0x[0-9a-fA-F]+[ij]?/)) {
- stream.tokenize = tokenBase;
- return 'number'; };
- if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?[ij]?/)) { return 'number'; };
- if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?[ij]?/)) { return 'number'; };
- }
- if (stream.match(wordRegexp(['nan','NaN','inf','Inf']))) { return 'number'; };
-
- // Handle Strings
- if (stream.match(/^"([^"]|(""))*"/)) { return 'string'; } ;
- if (stream.match(/^'([^']|(''))*'/)) { return 'string'; } ;
-
- // Handle words
- if (stream.match(keywords)) { return 'keyword'; } ;
- if (stream.match(builtins)) { return 'builtin'; } ;
- if (stream.match(identifiers)) { return 'variable'; } ;
-
- if (stream.match(singleOperators) || stream.match(doubleOperators)) { return 'operator'; };
- if (stream.match(singleDelimiters) || stream.match(doubleDelimiters) || stream.match(tripleDelimiters)) { return null; };
-
- if (stream.match(expressionEnd)) {
- state.tokenize = tokenTranspose;
- return null;
- };
-
-
- // Handle non-detected items
- stream.next();
- return 'error';
- };
-
-
- return {
- startState: function() {
- return {
- tokenize: tokenBase
- };
- },
-
- token: function(stream, state) {
- var style = state.tokenize(stream, state);
- if (style === 'number' || style === 'variable'){
- state.tokenize = tokenTranspose;
- }
- return style;
- }
- };
-});
-
-CodeMirror.defineMIME("text/x-octave", "octave");
diff --git a/src/xblock_problem/capa/templates/matlabinput.html b/src/xblock_problem/capa/templates/matlabinput.html
deleted file mode 100644
index cd3a0276..00000000
--- a/src/xblock_problem/capa/templates/matlabinput.html
+++ /dev/null
@@ -1,121 +0,0 @@
-
-
-
{{ value }}
-
- {% include "status_span.html" with status=status status_id=id %}
- {% if status == 'queued' %}{{ queue_len }}{% endif %}
- {% if hidden %}{% endif %}
-
{", "")
- output_list = output_string.split(",")
- for index, value in enumerate(output_list):
- output_list[index] = value.replace("u'", "'").strip()
-
- expected_string = """
- \'matlab_editor_js\': \'/dummy-static/js/vendor/CodeMirror/octave.js\',
- \'value\': \'print "good evening"\', \'hidden\': \'\',
- \'msg\': \'Submitted. As soon as a response is returned, this message will be replaced by that feedback.\',
- \'status\': Status(\'queued\'), \'response_data\': {}, \'queue_msg\': \'\', \'mode\': \'\',
- \'id\': \'prob_1_2\', \'queue_len\': \'3\', \'tabsize\': 4, \'STATIC_URL\': \'/dummy-static/\',
- \'linenumbers\': \'true\', \'cols\': \'80\', \'button_enabled\': True, \'rows\': \'10\',
- \'still_running_msg\': \'Your code is still being run. Refresh the page to see updates.\',
- \'describedby_html\': Markup(\'aria-describedby="status_prob_1_2"\')"""
- expected_list = (textwrap.dedent(expected_string).replace("\n", " ").strip()).split(",")
- for index, value in enumerate(expected_list):
- expected_list[index] = value.replace("u'", "'").strip()
- six.assertCountEqual(self, output_list, expected_list)
-
- # test html, that is correct HTML5 html, but is not parsable by XML parser.
- old_render_template = self.the_input.capa_system.render_template
- self.the_input.capa_system.render_template = lambda *args: textwrap.dedent(
- "
"
- ""
- "
Right click "
- "here "
- 'and click "Save As" to download the file
'
- "
"
- ).replace("\n", "")
-
- output = self.the_input.get_html()
- elements = []
- element_tags = []
- element_keys = []
- for element in output.iter():
- elements.append(element)
- element_tags.append(element.tag)
- element_keys.append(element.keys())
- assert element_tags.count("div") == 4
- assert element_tags.count("audio") == 1
- audio_index = element_tags.index("audio")
-
- six.assertCountEqual(self, element_keys[audio_index], ["autobuffer", "controls", "autoplay", "src"])
- assert elements[audio_index].get("src") == "data:audio/wav;base64="
- assert elements[audio_index].text == "Audio is not supported on this browser."
- href_index = element_keys.index(["href"])
- assert elements[href_index].get("href") == "https://endpoint.mss-mathworks.com/media/filename.wav"
- id_index = element_keys.index(["id"])
- assert elements[id_index].get("id") == "mwAudioPlaceHolder"
- output_string = etree.tostring(output).decode("utf-8")
-
- # check that exception is raised during parsing for html.
- self.the_input.capa_system.render_template = lambda *args: "
-
- if Conditionally execute statements.
- The general form of the if statement is
-
- if expression
- statements
- ELSEIF expression
- statements
- ELSE
- statements
- END
-
- The statements are executed if the real part of the expression
- has all non-zero elements. The ELSE and ELSEIF parts are optional.
- Zero or more ELSEIF parts can be used as well as nested if's.
- The expression is usually of the form expr rop expr where
- rop is ==, <, >, <=, >=, or ~=.
-
-
- Example
- if I == J
- A(I,J) = 2;
- elseif abs(I-J) == 1
- A(I,J) = -1;
- else
- A(I,J) = 0;
- end
-
- See also relop,
- else,
- elseif,
- end,
- for,
- while,
- switch.
-
- Reference page in Help browser
- doc if
-
-
if Conditionally execute '
- "statements.\nThe general form of the if statement is\n\n"
- " if expression\n statements\n ELSEIF expression\n"
- " statements\n ELSE\n statements\n END\n\nThe statements are "
- "executed if the real part of the expression \nhas all non-zero elements. "
- "The ELSE and ELSEIF parts are optional.\nZero or more ELSEIF parts can be "
- "used as well as nested if's.\nThe expression is usually "
- "of the form expr rop expr where \nrop is ==, <, >, <=, >=, or "
- '~=.\n\n\nExample\n if I == J\n A(I,J) = 2;\n elseif abs(I-J) '
- "== 1\n A(I,J) = -1;\n else\n A(I,J) = 0;\n end\n\nSee also "
- "relop, else, elseif, end, for, "
- "while, switch.\n\nReference page in Help browser\n "
- "doc if\n\n
\n"
- )
-
- received = fromstring(context["queue_msg"])
- html_tree_equal(received, expected)
-
- def test_rendering_with_invalid_queue_msg(self):
- """Ensure invalid queue messages are sanitized and handled."""
- self.the_input.queue_msg = (
- "
"
- "\nans =\n\n\u0002\n\n
"
- )
- context = self.the_input._get_render_context() # pylint: disable=protected-access
-
- self.maxDiff = None
- prob_id = "prob_1_2"
- expected = {
- "STATIC_URL": "/dummy-static/",
- "id": prob_id,
- "value": 'print "good evening"',
- "status": inputtypes.Status("queued"),
- "msg": self.the_input.submitted_msg,
- "mode": self.mode,
- "rows": self.rows,
- "cols": self.cols,
- "queue_msg": "Error running code.",
- "linenumbers": "true",
- "hidden": "",
- "tabsize": int(self.tabsize),
- "button_enabled": True,
- "queue_len": "3",
- "matlab_editor_js": "/dummy-static/js/vendor/CodeMirror/octave.js",
- "still_running_msg": "Your code is still being run. Refresh the page to see updates.",
- "response_data": {},
- "describedby_html": f'aria-describedby="status_{prob_id}"',
- }
- assert context == expected
- self.the_input.capa_system.render_template = DemoSystem().render_template
- self.the_input.get_html() # Should not raise an exception
-
- def test_matlab_queue_message_allowed_tags(self):
- """
- Test allowed tags.
- """
- allowed_tags = ["div", "p", "audio", "pre", "span"]
- for tag in allowed_tags:
- queue_msg = f"<{tag}>Test message{tag}>"
- state = {
- "input_state": {"queue_msg": queue_msg},
- "status": "queued",
- }
- elt = etree.fromstring(self.xml)
- the_input = self.input_class(mock_capa_system(), elt, state)
- assert the_input.queue_msg == queue_msg
-
- def test_matlab_queue_message_not_allowed_tag(self):
- """
- Test not allowed tag.
- """
- not_allowed_tag = "script"
- queue_msg = f"<{not_allowed_tag}>Test message{not_allowed_tag}>"
- state = {
- "input_state": {"queue_msg": queue_msg},
- "status": "queued",
- }
- elt = etree.fromstring(self.xml)
- the_input = self.input_class(mock_capa_system(), elt, state)
- expected = ""
- assert the_input.queue_msg == expected
-
- def test_matlab_sanitize_msg(self):
- """
- Check that the_input.msg is sanitized.
- """
- not_allowed_tag = "script"
- self.the_input.msg = f"<{not_allowed_tag}>Test message{not_allowed_tag}>"
- expected = ""
- assert self.the_input._get_render_context()["msg"] == expected # pylint: disable=protected-access
+ assert context["value"] == 'print "good evening"'
+ assert context["status"] == inputtypes.Status("queued")
+ assert context["queue_len"] == "3"
+ assert context["mode"] == ""
+ assert "matlab" not in the_input.get_html().xpath("string()").lower()
def html_tree_equal(received, expected):
diff --git a/src/xblock_problem/capa/tests/test_responsetypes.py b/src/xblock_problem/capa/tests/test_responsetypes.py
index ac939c5b..9786463a 100644
--- a/src/xblock_problem/capa/tests/test_responsetypes.py
+++ b/src/xblock_problem/capa/tests/test_responsetypes.py
@@ -955,6 +955,19 @@ def make_queuestate(key, time):
timestr = datetime.strftime(time, DATEFORMAT)
return {"key": key, "time": timestr}
+ def test_get_score_without_xqueue(self):
+ """
+ Without an xqueue service, as in Studio, a submission is not queued and the learner
+ is told no grader is set up.
+ """
+ responder = list(self.problem.responders.values())[0]
+ responder.capa_system.xqueue = None
+
+ cmap = responder.get_score({responder.answer_id: "def square(x): return x * x"})
+
+ assert not cmap.is_queued(responder.answer_id)
+ assert cmap.get_msg(responder.answer_id) == "Error: No grader has been set up for this problem."
+
def test_is_queued(self):
"""
Simple test of whether LoncapaProblem knows when it's been queued
diff --git a/src/xblock_problem/capa/tests/test_util.py b/src/xblock_problem/capa/tests/test_util.py
index d7b6cfd9..e87caac5 100644
--- a/src/xblock_problem/capa/tests/test_util.py
+++ b/src/xblock_problem/capa/tests/test_util.py
@@ -13,7 +13,6 @@
contextualize_text,
get_inner_html_from_xpath,
remove_markup,
- sanitize_html,
)
@@ -118,20 +117,6 @@ def test_compare_with_tolerance(self): # pylint: disable=too-many-statements
result = compare_with_tolerance(111.0, complex(100.0, 0), "10%", True)
assert result
- def test_sanitize_html(self):
- """
- Test for html sanitization with nh3.
- """
- allowed_tags = ["div", "p", "audio", "pre", "span"]
- for tag in allowed_tags:
- queue_msg = f"<{tag}>Test message{tag}>"
- assert sanitize_html(queue_msg) == queue_msg
-
- not_allowed_tag = "script"
- queue_msg = f"<{not_allowed_tag}>Test message{not_allowed_tag}>"
- expected = ""
- assert sanitize_html(queue_msg) == expected
-
def test_get_inner_html_from_xpath(self):
"""
Test for getting inner html as string from xpath node.
diff --git a/src/xblock_problem/capa/tests/test_xqueue_interface.py b/src/xblock_problem/capa/tests/test_xqueue_interface.py
index e6b0b4c3..26b52fee 100644
--- a/src/xblock_problem/capa/tests/test_xqueue_interface.py
+++ b/src/xblock_problem/capa/tests/test_xqueue_interface.py
@@ -4,39 +4,48 @@
from unittest.mock import Mock, patch
import pytest
+from submissions.errors import SubmissionInternalError, SubmissionRequestError
-from xblock_problem.capa.xqueue_interface import XQueueInterface
+from xblock_problem.capa.errors import RuntimeErrorSubmission
+from xblock_problem.capa.xqueue_interface import XQueueInterface, make_xheader
@pytest.mark.django_db
@patch("xblock_problem.capa.xqueue_submission.XQueueInterfaceSubmission.send_to_submission")
-def test_send_to_queue_with_flag_enabled(mock_send_to_submission):
- """Test send_to_queue when the waffle flag is enabled."""
- url = "http://example.com/xqueue"
- django_auth = {"username": "user", "password": "pass"}
- block = Mock() # Mock block for the constructor
- xqueue_interface = XQueueInterface(url, django_auth, block=block, use_submission_service=True)
-
- header = json.dumps(
- {
- "lms_callback_url": (
- "http://example.com/courses/course-v1:test_org+test_course+test_run/xqueue/block@item_id/type@problem"
- ),
- "lms_key": "default",
- }
- )
+def test_send_to_queue(mock_send_to_submission):
+ """send_to_queue hands the header, body and queue key to edx-submissions."""
+ xqueue_interface = XQueueInterface(block=Mock())
+
+ header = make_xheader(lms_key="default", queue_name="testqueue")
body = json.dumps(
{
"student_info": json.dumps({"anonymous_student_id": "student_id"}),
"student_response": "student_answer",
}
)
- files_to_upload = None
mock_send_to_submission.return_value = {"submission": "mock_submission"}
- error, msg = xqueue_interface.send_to_queue(header, body, files_to_upload) # pylint: disable=unused-variable
+ error, msg = xqueue_interface.send_to_queue(header, body)
mock_send_to_submission.assert_called_once_with(header, body, "default", {})
+ assert error == 0
+ assert msg == ""
+
+
+@pytest.mark.django_db
+@patch("xblock_problem.capa.xqueue_submission.XQueueInterfaceSubmission.send_to_submission")
+def test_send_to_queue_with_files(mock_send_to_submission):
+ """Uploaded files are passed through keyed by file name."""
+ xqueue_interface = XQueueInterface(block=Mock())
+ header = make_xheader(lms_key="default", queue_name="testqueue")
+ body = json.dumps({"student_info": json.dumps({"anonymous_student_id": "student_id"})})
+ prog = Mock()
+ prog.name = "prog1.py"
+
+ mock_send_to_submission.return_value = {"submission": "mock_submission"}
+ error, _ = xqueue_interface.send_to_queue(header, body, files_to_upload=[prog])
+
+ mock_send_to_submission.assert_called_once_with(header, body, "default", {"prog1.py": prog})
assert not error
@@ -47,10 +56,8 @@ def test_send_to_queue_reports_submission_service_error(mock_send_to_submission)
If edx-submissions can't create the submission, send_to_queue returns an error
so the problem tells the learner, instead of reporting success.
"""
- xqueue_interface = XQueueInterface(
- "http://example.com/xqueue", {"username": "user", "password": "pass"}, block=Mock(), use_submission_service=True
- )
- header = json.dumps({"lms_callback_url": "http://example.com/callback", "lms_key": "default"})
+ xqueue_interface = XQueueInterface(block=Mock())
+ header = make_xheader(lms_key="default", queue_name="testqueue")
body = json.dumps({"student_info": json.dumps({"anonymous_student_id": "student_id"})})
mock_send_to_submission.return_value = {"error": "Validation error: The field 'student_response' does not exist."}
@@ -61,35 +68,31 @@ def test_send_to_queue_reports_submission_service_error(mock_send_to_submission)
@pytest.mark.django_db
-@patch("xblock_problem.capa.xqueue_interface.XQueueInterface._http_post")
-def test_send_to_queue_with_flag_disabled(mock_http_post):
- """Test send_to_queue when the waffle flag is disabled."""
- url = "http://example.com/xqueue"
- django_auth = {"username": "user", "password": "pass"}
- block = Mock() # Mock block for the constructor
- xqueue_interface = XQueueInterface(url, django_auth, block=block, use_submission_service=False)
-
- header = json.dumps(
- {
- "lms_callback_url": (
- "http://example.com/courses/course-v1:test_org+test_course+test_run/xqueue/block@item_id/type@problem"
- ),
- "lms_key": "default",
- }
- )
- body = json.dumps(
- {
- "student_info": json.dumps({"anonymous_student_id": "student_id"}),
- "student_response": "student_answer",
- }
- )
- files_to_upload = None
+@pytest.mark.parametrize(
+ "exception, expected_msg",
+ [
+ (SubmissionInternalError("database is away "), "the grading queue is unavailable"),
+ (RuntimeErrorSubmission("Database access not allowed"), "the grading queue is unavailable"),
+ (
+ SubmissionRequestError(field_errors={"answer": ["Maximum answer size exceeded."]}),
+ "the submission was rejected",
+ ),
+ ],
+)
+@patch("xblock_problem.capa.xqueue_submission.XQueueInterfaceSubmission.send_to_submission")
+def test_send_to_queue_reports_exceptions_as_errors(mock_send_to_submission, exception, expected_msg):
+ """
+ A failure inside edx-submissions comes back as an error code and a fixed message, the way
+ a connection failure to the XQueue service used to, so the problem can tell the learner to
+ try again instead of raising. The message is fixed because display.js shows it as HTML
+ and the exception text can carry the learner's answer.
+ """
+ xqueue_interface = XQueueInterface(block=Mock())
+ header = make_xheader(lms_key="default", queue_name="testqueue")
+ body = json.dumps({"student_info": json.dumps({"anonymous_student_id": "student_id"})})
- mock_http_post.return_value = (0, "Submission sent successfully")
- error, msg = xqueue_interface.send_to_queue(header, body, files_to_upload) # pylint: disable=unused-variable
+ mock_send_to_submission.side_effect = exception
+ error, msg = xqueue_interface.send_to_queue(header, body)
- mock_http_post.assert_called_once_with(
- "http://example.com/xqueue/xqueue/submit/",
- {"xqueue_header": header, "xqueue_body": body},
- files={},
- )
+ assert error == 1
+ assert msg == expected_msg
diff --git a/src/xblock_problem/capa/tests/test_xqueue_submission.py b/src/xblock_problem/capa/tests/test_xqueue_submission.py
index 97205f32..913e65c9 100644
--- a/src/xblock_problem/capa/tests/test_xqueue_submission.py
+++ b/src/xblock_problem/capa/tests/test_xqueue_submission.py
@@ -10,6 +10,7 @@
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from xblock.fields import ScopeIds
+from xblock_problem.capa.xqueue_interface import make_xheader
from xblock_problem.capa.xqueue_submission import XQueueInterfaceSubmission
@@ -30,7 +31,7 @@ def test_get_submission_params(xqueue_service): # pylint: disable=redefined-out
"""
Test extracting item data from an xqueue submission.
"""
- header = json.dumps({"lms_callback_url": "http://example.com/callback", "queue_name": "default"})
+ header = make_xheader(lms_key="default", queue_name="default")
payload = json.dumps(
{
"student_info": json.dumps({"anonymous_student_id": "student_id"}),
@@ -62,14 +63,7 @@ def test_send_to_submission(mock_create_external_grader_detail, xqueue_service):
"""
Test sending a submission to the grading system.
"""
- header = json.dumps(
- {
- "lms_callback_url": (
- "http://example.com/courses/course-v1:test_org+test_course+test_run/xqueue/5/"
- "block-v1:test_org+test_course+test_run+type@problem+block@ExampleProblem/"
- ),
- }
- )
+ header = make_xheader(lms_key="default", queue_name="default")
body = json.dumps(
{
"student_info": json.dumps({"anonymous_student_id": "student_id"}),
@@ -266,13 +260,7 @@ def test_send_to_submission_with_missing_fields(mock_create_external_grader_deta
"""
Test send_to_submission with missing required fields.
"""
- header = json.dumps(
- {
- "lms_callback_url": (
- "http://example.com/courses/course-v1:test_org+test_course+test_run/xqueue/5/block@item_id/"
- )
- }
- )
+ header = make_xheader(lms_key="default", queue_name="default")
body = json.dumps(
{
"student_info": json.dumps({"anonymous_student_id": "student_id"}),
diff --git a/src/xblock_problem/capa/util.py b/src/xblock_problem/capa/util.py
index ae705f6c..26b4b227 100644
--- a/src/xblock_problem/capa/util.py
+++ b/src/xblock_problem/capa/util.py
@@ -176,26 +176,6 @@ def find_with_default(node, path, default):
return default
-def sanitize_html(html_code):
- """
- Sanitize html_code for safe embed on LMS pages.
-
- Used to sanitize XQueue responses from Matlab.
- """
- attributes = nh3.ALLOWED_ATTRIBUTES.copy()
- attributes.update(
- {
- "*": {"class", "style", "id"},
- "audio": {"controls", "autobuffer", "autoplay", "src"},
- "img": {"src", "width", "height", "class"},
- }
- )
- output = nh3.clean(
- html_code, tags=nh3.ALLOWED_TAGS | {"div", "p", "audio", "pre", "img", "span"}, attributes=attributes
- )
- return output
-
-
def get_inner_html_from_xpath(xpath_node):
"""
Returns inner html as string from xpath node.
diff --git a/src/xblock_problem/capa/xqueue_interface.py b/src/xblock_problem/capa/xqueue_interface.py
index e168429a..97f0b375 100644
--- a/src/xblock_problem/capa/xqueue_interface.py
+++ b/src/xblock_problem/capa/xqueue_interface.py
@@ -1,5 +1,12 @@
"""
-LMS Interface to external queueing system (xqueue)
+Interface for queueing external grader submissions.
+
+Submissions go to edx-submissions, which stores them in the LMS and serves
+them to graders such as xqueue-watcher through its XQueue-compatible API.
+The header built here is an internal envelope: edx-submissions reads the
+queue name and the queue key out of it and builds its own header for the
+grader. The queue key format is the one the retired XQueue service used,
+since the problem's correct map still stores it.
"""
import hashlib
@@ -7,9 +14,9 @@
import logging
from typing import TYPE_CHECKING
-import requests
-from requests.auth import HTTPBasicAuth
+from submissions.errors import SubmissionError, SubmissionRequestError
+from xblock_problem.capa.errors import XQueueSubmissionError
from xblock_problem.capa.xqueue_submission import XQueueInterfaceSubmission
if TYPE_CHECKING:
@@ -18,13 +25,6 @@
log = logging.getLogger(__name__)
DATEFORMAT = "%Y%m%d%H%M%S"
-XQUEUE_METRIC_NAME = "edxapp.xqueue"
-
-# Wait time for response from Xqueue.
-XQUEUE_TIMEOUT = 35 # seconds
-CONNECT_TIMEOUT = 3.05 # seconds
-READ_TIMEOUT = 10 # seconds
-
def make_hashkey(seed):
"""
@@ -35,155 +35,65 @@ def make_hashkey(seed):
return h.hexdigest()
-def make_xheader(lms_callback_url, lms_key, queue_name):
+def make_xheader(lms_key, queue_name):
"""
- Generate header for delivery and reply of queue request.
+ Generate the header that accompanies a queue request.
- Xqueue header is a JSON-serialized dict::
+ The header is a JSON-serialized dict::
- { 'lms_callback_url': url to which xqueue will return the request (string),
- 'lms_key': secret key used by LMS to protect its state (string),
- 'queue_name': designate a specific queue within xqueue server, e.g. 'MITx-6.00x' (string)
+ { 'lms_key': secret key used by LMS to match the grader's reply to the request (string),
+ 'queue_name': the queue the grader polls, e.g. 'MITx-6.00x' (string)
}
"""
- return json.dumps({"lms_callback_url": lms_callback_url, "lms_key": lms_key, "queue_name": queue_name})
-
-
-def parse_xreply(xreply):
- """
- Parse the reply from xqueue. Messages are JSON-serialized dict::
-
- { 'return_code': 0 (success), 1 (fail)
- 'content': Message from xqueue (string)
- }
- """
- try:
- xreply = json.loads(xreply)
- except ValueError as err:
- log.error(err)
- return (1, "unexpected reply from server")
-
- return_code = xreply["return_code"]
- content = xreply["content"]
-
- return (return_code, content)
+ return json.dumps({"lms_key": lms_key, "queue_name": queue_name})
class XQueueInterface:
- """Initializes the XQueue interface."""
-
- def __init__(
- self,
- url: str,
- django_auth: dict[str, str],
- requests_auth: HTTPBasicAuth | None = None,
- block: "ProblemBlock" = None,
- use_submission_service: bool = False,
- ):
- """
- Initializes the XQueue interface.
+ """Queues external grader submissions through edx-submissions."""
+ def __init__(self, block: "ProblemBlock"):
+ """
Args:
- url (str): The URL of the XQueue service.
- django_auth (Dict[str, str]): Authentication credentials for Django.
- requests_auth (Optional[HTTPBasicAuth], optional): Authentication for HTTP requests. Defaults to None.
- block ('ProblemBlock', optional): Added as a parameter only to extract the course_id
- to check the course waffle flag `send_to_submission_course.enable`.
- This can be removed after the legacy xqueue is deprecated. Defaults to None.
- use_submission_service (bool): If True, use the edx-submissions service instead of XQueue.
+ block (ProblemBlock): The problem the submissions belong to. edx-submissions
+ records the course, the problem and its maximum score with each one.
"""
- self.url = url
- self.auth = django_auth
- self.session = requests.Session()
- self.session.auth = requests_auth
self.block = block
- self.submission = XQueueInterfaceSubmission(self.block)
- self.use_submission_service = use_submission_service
+ self.submission = XQueueInterfaceSubmission(block)
def send_to_queue(self, header, body, files_to_upload=None):
"""
- Submit a request to xqueue.
+ Queue a submission for an external grader.
header: JSON-serialized dict in the format described in 'xqueue_interface.make_xheader'
- body: Serialized data for the receipient behind the queueing service. The operation of
- xqueue is agnostic to the contents of 'body'
+ body: Serialized data for the recipient behind the queueing service. The operation of
+ the queue is agnostic to the contents of 'body'
- files_to_upload: List of file objects to be uploaded to xqueue along with queue request
+ files_to_upload: List of file objects to be stored along with the queue request
Returns (error_code, msg) where error_code != 0 indicates an error
"""
-
- # log the send to xqueue
- header_info = json.loads(header)
- _queue_name = header_info.get("queue_name", "")
-
- # Attempt to send to queue
- error, msg = self._send_to_queue(header, body, files_to_upload)
-
- # Log in, then try again
- if error and (msg == "login_required"):
- error, content = self._login()
- if error != 0:
- # when the login fails
- log.debug("Failed to login to queue: %s", content)
- return (error, content)
- if files_to_upload is not None:
- # Need to rewind file pointers
- for f in files_to_upload:
- f.seek(0)
- error, msg = self._send_to_queue(header, body, files_to_upload)
-
- return error, msg
-
- def _login(self):
- payload = {"username": self.auth["username"], "password": self.auth["password"]}
- return self._http_post(self.url + "/xqueue/login/", payload)
-
- def _send_to_queue(self, header, body, files_to_upload):
- """Send the problem submission to XQueue, handling legacy fallback and edX submission logic."""
-
- payload = {"xqueue_header": header, "xqueue_body": body}
- files = {}
- if files_to_upload is not None:
- for f in files_to_upload:
- files.update({f.name: f})
-
- if self.block is None:
- # XQueueInterface: if self.block is None, falling back to legacy xqueue submission.
- log.error(
- "Unexpected None block: falling back to legacy xqueue submission. "
- "This may indicate a problem with the xqueue transition."
- )
- return self._http_post(self.url + "/xqueue/submit/", payload, files=files)
+ files = {f.name: f for f in files_to_upload or []}
header_info = json.loads(header)
queue_key = header_info["lms_key"]
- if self.use_submission_service:
- result = self.submission.send_to_submission(header, body, queue_key, files)
- # send_to_submission reports submissions it couldn't create as {"error": msg}. Pass that
- # back as an error so the learner is told it wasn't queued, rather than waiting on it forever.
- if isinstance(result, dict) and "error" in result:
- return 1, result["error"]
- return None, ""
-
- return self._http_post(self.url + "/xqueue/submit/", payload, files=files)
-
- def _http_post(self, url, data, files=None):
- """Send an HTTP POST request and handle connection errors, timeouts, and unexpected status codes."""
-
+ # Report anything that keeps the submission from being queued as an error, so the
+ # learner is told to try again rather than waiting on a submission that doesn't exist.
+ # send_to_submission returns {"error": msg} for a bad request body and raises for the
+ # rest; edx-submissions raises SubmissionError for its own failures.
+ #
+ # The message goes in front of the learner, and display.js shows it as HTML (see
+ # gentle_alert()), so it is a fixed string: the exception text can carry the
+ # learner's own answer. The details go to the log.
try:
- response = self.session.post(url, data=data, files=files, timeout=(CONNECT_TIMEOUT, READ_TIMEOUT))
- except requests.exceptions.ConnectionError as err:
- log.error(err)
- return 1, "cannot connect to server"
-
- except requests.exceptions.ReadTimeout as err:
- log.error(err)
- return 1, "failed to read from the server"
-
- if response.status_code not in [200]:
- return 1, f"unexpected HTTP status code [{response.status_code}]"
-
- return parse_xreply(response.text)
+ result = self.submission.send_to_submission(header, body, queue_key, files)
+ except SubmissionRequestError:
+ log.exception("Submission for %s was rejected by edx-submissions", self.block.usage_key)
+ return 1, "the submission was rejected"
+ except (SubmissionError, XQueueSubmissionError):
+ log.exception("Could not queue submission for %s", self.block.usage_key)
+ return 1, "the grading queue is unavailable"
+ if isinstance(result, dict) and "error" in result:
+ return 1, result["error"]
+ return 0, ""
diff --git a/src/xblock_problem/tests/__init__.py b/src/xblock_problem/tests/__init__.py
index 9f937c78..59c10726 100644
--- a/src/xblock_problem/tests/__init__.py
+++ b/src/xblock_problem/tests/__init__.py
@@ -8,7 +8,6 @@
from django.conf import settings
from opaque_keys.edx.locator import CourseLocator
from path import Path as path
-from requests.auth import HTTPBasicAuth
from xblock.reference.user_service import UserService, XBlockUser
from xblock.test.tools import TestRuntime
@@ -129,24 +128,10 @@ class StubXQueueService:
def __init__(self):
"""Initialize the stubbed XQueueService instance."""
- basic_auth = settings.XQUEUE_INTERFACE.get("basic_auth")
- requests_auth = HTTPBasicAuth(*basic_auth) if basic_auth else None
-
- self.interface = XQueueInterface(
- settings.XQUEUE_INTERFACE["url"],
- settings.XQUEUE_INTERFACE["django_auth"],
- requests_auth,
- block=MagicMock(),
- use_submission_service=False,
- )
+ self.interface = XQueueInterface(block=MagicMock())
self.default_queuename = "testqueue"
-
self.waittime = getattr(settings, "XQUEUE_WAITTIME_BETWEEN_REQUESTS", 5)
- def construct_callback(self, dispatch="score_update"):
- """A callback url method to use in tests."""
- return dispatch
-
class TestDescriptorSystem(TestRuntime):
"""
diff --git a/src/xblock_problem/tests/test_capa_block.py b/src/xblock_problem/tests/test_capa_block.py
index ebfd03b3..74de72ea 100644
--- a/src/xblock_problem/tests/test_capa_block.py
+++ b/src/xblock_problem/tests/test_capa_block.py
@@ -15,13 +15,13 @@
import ddt
import pytest
-import requests
import webob
from codejail.safe_exec import SafeExecException
from django.test import override_settings
from django.utils.encoding import smart_str
from lxml import etree
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
+from submissions.errors import SubmissionInternalError
from web_fragments.fragment import Fragment
from webob.multidict import MultiDict
from xblock.exceptions import NotFoundError
@@ -34,6 +34,7 @@
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 xblock_problem.tests import DATA_DIR
from ..block import RANDOMIZATION, SHOWANSWER
@@ -184,6 +185,18 @@ def create( # pylint: disable=too-many-arguments,too-many-positional-arguments
return block
+CODE_PROBLEM_XML = textwrap.dedent("""\
+
+
+
+
+ {"grader": "ps1/f.py"}
+
+
+
+""")
+
+
class CapaFactoryWithFiles(CapaFactory):
"""
A factory for creating a Capa problem with files attached.
@@ -296,21 +309,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")
@@ -1268,9 +1266,51 @@ def test_submit_problem_queued(self):
assert block.attempts == 1
@pytest.mark.django_db
- @patch.object(XQueueInterface, "_http_post")
+ def test_submit_problem_queues_in_edx_submissions(self):
+ """
+ A submission to a code problem ends up as a pending ExternalGraderDetail row, with
+ nothing mocked. This is the only path external grader submissions take now.
+ """
+ # Imported here: submissions.models needs the Django apps loaded, and the docs
+ # build imports this module without them.
+ from submissions.models import ExternalGraderDetail # pylint: disable=import-outside-toplevel
+
+ block = CapaFactory.create(xml=CODE_PROBLEM_XML)
+ # The stub service builds its XQueueInterface around a MagicMock block.
+ block.runtime.service(block, "xqueue").interface = XQueueInterface(block)
+
+ block.submit_problem({CapaFactory.input_key(): "print('hi')"})
+
+ detail = ExternalGraderDetail.objects.get()
+ assert detail.status == "pending"
+ assert detail.queue_name == "test-queue"
+ assert detail.grader_file_name == "ps1/f.py"
+ assert detail.submission.answer == "print('hi')"
+ assert detail.submission.student_item.item_id == str(block.usage_key)
+ assert block.lcp.correct_map.is_right_queuekey(CapaFactory.answer_key(), detail.queue_key)
+
+ @pytest.mark.django_db
+ @patch.object(XQueueInterfaceSubmission, "send_to_submission")
+ def test_submit_problem_queue_failure_does_not_use_an_attempt(self, mock_xqueue_post):
+ """
+ If the submission can't be queued, the learner is told so and keeps the attempt,
+ instead of using their last attempt on a submission that was never queued.
+ """
+ mock_xqueue_post.side_effect = SubmissionInternalError("database is away")
+ block = CapaFactory.create(xml=CODE_PROBLEM_XML, max_attempts=1)
+ block.runtime.service(block, "xqueue").interface = XQueueInterface(block)
+
+ result = block.submit_problem({CapaFactory.input_key(): "print('hi')"})
+
+ assert "Unable to deliver your submission to grader" in result["success"]
+ assert block.attempts == 0
+ assert not block.closed()
+ assert not block.lcp.correct_map.is_queued(CapaFactory.answer_key())
+
+ @pytest.mark.django_db
+ @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.
@@ -1282,8 +1322,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 = {
@@ -1293,51 +1333,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()))
- for fpath, fileobj in kwargs["files"].items():
+ files = mock_xqueue_post.call_args.args[3]
+ self.assertCountEqual(fpaths, list(files.keys()))
+ 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.
@@ -1352,8 +1365,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 = []
@@ -1365,11 +1378,37 @@ 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()))
- for fpath, fileobj in kwargs["files"].items():
+ files = mock_xqueue_post.call_args.args[3]
+ self.assertCountEqual(fnames, list(files.keys()))
+ for fpath, fileobj in files.items():
assert fpath == fileobj.name
+ @pytest.mark.django_db
+ @patch.object(XQueueInterfaceSubmission, "send_to_submission")
+ def test_submit_problem_matlabinput_is_refused(self, mock_xqueue_post):
+ """
+ A legacy problem still loads, but a submission to it is refused
+ without queueing anything or using an attempt: there is no MATLAB grader any more.
+ """
+ xml = textwrap.dedent("""\
+
+
+
+
+ {"grader": "f.py"}
+
+
+
+ """)
+ block = CapaFactory.create(xml=xml, max_attempts=1)
+
+ result = block.submit_problem({CapaFactory.input_key(): "disp('hi')"})
+
+ assert "MATLAB problems can no longer be graded" in result["success"]
+ assert block.attempts == 0
+ assert not block.closed()
+ mock_xqueue_post.assert_not_called()
+
def test_submit_problem_error(self):
"""Ensure expected grading errors return messages without incrementing attempts."""
@@ -4004,7 +4043,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"]
@@ -4017,8 +4056,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/test_settings.py b/test_settings.py
index e2edec27..6f639091 100644
--- a/test_settings.py
+++ b/test_settings.py
@@ -4,9 +4,6 @@
from pathlib import Path
-from django.http import HttpResponse
-from django.urls import re_path
-
BASE_DIR = Path(__file__).resolve().parent
INSTALLED_APPS = [
"django.contrib.auth",
@@ -22,25 +19,11 @@
}
-def dummy_callback(_request, *_args, **_kwargs):
- """
- Minimal placeholder view for test URL patterns.
- Underscored arguments silence lint warnings for unused variables.
- """
- return HttpResponse("OK")
-
-
ROOT_URLCONF = type(
"URLConf",
(),
{
- "urlpatterns": [
- re_path(
- r"^courses/(?P.+)/xqueue/(?P[^/]+)/(?P.+)/(?P[^/]+)$",
- dummy_callback,
- name="xqueue_callback",
- ),
- ]
+ "urlpatterns": [],
},
)
@@ -66,13 +49,7 @@ def dummy_callback(_request, *_args, **_kwargs):
# CAPA External Code Evaluation #
-# Used with XQueue
XQUEUE_WAITTIME_BETWEEN_REQUESTS = 5 # seconds
-XQUEUE_INTERFACE = {
- "url": "http://localhost:18040",
- "basic_auth": ["edx", "edx"],
- "django_auth": {"username": "lms", "password": "password"},
-}
TEMPLATES = [
{