Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
2 changes: 1 addition & 1 deletion cms/djangoapps/contentstore/tests/test_export_git.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 0 additions & 8 deletions cms/envs/mock.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 5 additions & 5 deletions cms/lib/xblock/test/test_upstream_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"'
Expand Down Expand Up @@ -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
Expand All @@ -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"'
Expand All @@ -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.
Expand All @@ -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
Expand Down
6 changes: 3 additions & 3 deletions cms/templates/export.html
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ <h2 class="title">${_("About Exporting Courses")}</h2>
<p>${_("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
)}</p>
<p>${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(
<p>${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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, the Authoring MFE has its own copies of these strings (export page, export footer, export sidebar, import sidebar), so they need the same edit. Could you add that to the follow-ups in the description?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Went ahead and made the PR for it: openedx/frontend-app-authoring#3387 It's linked from the follow-ups in the description too.

em_start=HTML('<strong>'),
em_end=HTML("</strong>")
)}</p>
Expand Down Expand Up @@ -151,7 +151,7 @@ <h3 class="title-3">
em_end=HTML("</strong>")
)}</h3>
<ul class="list-details list-export-includes">
<li class="item-detail">${_("Values from Advanced Settings, including MATLAB API keys and LTI passports")}</li>
<li class="item-detail">${_("Values from Advanced Settings, including LTI passports")}</li>
<li class="item-detail">${_("Course Content (all Sections, Sub-sections, and Units)")}</li>
<li class="item-detail">${_("Course Structure")}</li>
<li class="item-detail">${_("Individual Problems")}</li>
Expand Down Expand Up @@ -192,7 +192,7 @@ <h3 class="title-3">${_("What content is exported?")}</h3>
<li>${_("Course dates")}</li>
<li>${_("Grading policy")}</li>
<li>${_("Any group configurations")}</li>
<li>${_("Settings on the Advanced Settings page, including MATLAB API keys and LTI passports")}</li>
<li>${_("Settings on the Advanced Settings page, including LTI passports")}</li>
</ul>
<p>${_("The following content is not exported.")}</p>
<ul>
Expand Down
2 changes: 1 addition & 1 deletion cms/templates/import.html
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ <h3 class="title-3">${_("What content is imported?")}</h3>
<li>${_("Course dates")}</li>
<li>${_("Grading policy")}</li>
<li>${_("Any group configurations")}</li>
<li>${_("Settings on the Advanced Settings page, including MATLAB API keys and LTI passports")}</li>
<li>${_("Settings on the Advanced Settings page, including LTI passports")}</li>
</ul>
<p>${_("The following content is not imported.")}</p>
<ul>
Expand Down
49 changes: 5 additions & 44 deletions lms/djangoapps/courseware/block_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
88 changes: 0 additions & 88 deletions lms/djangoapps/courseware/tests/test_block_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(
Expand Down
6 changes: 4 additions & 2 deletions lms/djangoapps/courseware/tests/test_lti_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question: I'm curious why this LTI change is mixed up in here. It's not a problem if it is, but I'm curious if it's some weird knock-on effect of the XQueue/MATLAB removal, or just something that was noticed along the way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a knock-on from the xblocks-core bump, not from the removal itself. xblocks-core 3.1.0 started passing i18n_service to render_django_template in LTIBlock.preview_handler(openedx/xblocks-core#336), and master is still on 3.0.0, so this PR is the first to pull that in. The fix strips it the same way test_lti_constructor already does for student_view.

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):
Expand Down
39 changes: 28 additions & 11 deletions lms/djangoapps/courseware/tests/test_submitting_problems.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 = [
Expand All @@ -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": "<p>Good job</p>"}),
})

# 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):
Expand Down
Loading
Loading