chore: get rid of edx_six - not needed anymore (#32555)

* chore: get rid of edx_six - not needed anymore
* chore: remove reference to TODO that was completed.
This commit is contained in:
Braden MacDonald
2023-07-10 11:16:57 -07:00
committed by GitHub
parent 7a89f2e5d3
commit 162175f0c4
5 changed files with 46 additions and 71 deletions

View File

@@ -1,8 +1,6 @@
"""
Tests for validate Internationalization and XBlock i18n service.
"""
import gettext
from unittest import mock, skip
@@ -17,7 +15,6 @@ from xmodule.tests.test_export import PureXBlock
from cms.djangoapps.contentstore.tests.utils import AjaxEnabledTestClient
from cms.djangoapps.contentstore.views.preview import _prepare_runtime_for_preview
from common.djangoapps.student.tests.factories import UserFactory
from openedx.core.lib.edx_six import get_gettext
class FakeTranslations(XBlockI18nService):
@@ -94,7 +91,7 @@ class TestXBlockI18nService(ModuleStoreTestCase):
def __init__(self, module):
self.module = module
self.old_ugettext = get_gettext(module)
self.old_ugettext = module.gettext
def __enter__(self):
def new_ugettext(*args, **kwargs):
@@ -152,9 +149,9 @@ class TestXBlockI18nService(ModuleStoreTestCase):
with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,
languages=[get_language()])):
i18n_service = self.get_block_i18n_service(self.block)
self.assertEqual(get_gettext(i18n_service)('Hello'), 'Hello')
self.assertNotEqual(get_gettext(i18n_service)('Hello'), 'fr-hello-world')
self.assertNotEqual(get_gettext(i18n_service)('Hello'), 'es-hello-world')
self.assertEqual(i18n_service.gettext('Hello'), 'Hello')
self.assertNotEqual(i18n_service.gettext('Hello'), 'fr-hello-world')
self.assertNotEqual(i18n_service.gettext('Hello'), 'es-hello-world')
translation.activate("fr")
with mock.patch('gettext.translation', return_value=_translator(domain='text', localedir=localedir,

View File

@@ -1,12 +0,0 @@
"""
Extra methods to do some python 2 to 3 things we need to do in edx-platform.
This is internal and should not be referenced outside of the edx-platform repo.
"""
def get_gettext(o):
"""
In python 2 return the ugettext attribute. In python 3 return gettext.
"""
return o.gettext

View File

@@ -36,7 +36,6 @@ from xmodule.capa.correctmap import CorrectMap
from xmodule.capa.safe_exec import safe_exec
from xmodule.capa.util import contextualize_text, convert_files_to_filenames, get_course_id_from_capa_block
from openedx.core.djangolib.markup import HTML, Text
from openedx.core.lib.edx_six import get_gettext
from xmodule.stringify import stringify_children
# extra things displayed after "show answers" is pressed
@@ -483,7 +482,7 @@ class LoncapaProblem(object):
# an earlier submission, so for now skip these entirely.
# TODO: figure out where to get file submissions when rescoring.
if 'filesubmission' in responder.allowed_inputfields and student_answers is None:
_ = get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
raise Exception(_("Cannot rescore problems with possible file submissions"))
# use 'student_answers' only if it is provided, and if it might contain a file
@@ -580,7 +579,7 @@ class LoncapaProblem(object):
question_nr = int(answer_id.split('_')[-2]) - 1
return _("Question {}").format(question_nr)
_ = get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Some questions define a prompt with this format: >>This is a prompt<<
try:
prompt = self.problem_data[answer_id].get('label')
@@ -693,7 +692,7 @@ class LoncapaProblem(object):
choice-level explanations shown to a student after submission.
Does nothing if there is no targeted-feedback attribute.
"""
_ = get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Note that the modifications has been done, avoiding problems if called twice.
if hasattr(self, 'has_targeted'):
return

View File

@@ -59,7 +59,6 @@ from six import text_type
from xmodule.capa.xqueue_interface import XQUEUE_TIMEOUT
from openedx.core.djangolib.markup import HTML, Text
from openedx.core.lib import edx_six
from xmodule.stringify import stringify_children
from . import xqueue_interface
@@ -327,7 +326,7 @@ class InputTypeBase(object):
context = {
'id': self.input_id,
'value': self.value,
'status': Status(self.status, edx_six.get_gettext(self.capa_system.i18n)),
'status': Status(self.status, self.capa_system.i18n.gettext),
'msg': self.msg,
'response_data': self.response_data,
'STATIC_URL': self.capa_system.STATIC_URL,
@@ -459,7 +458,7 @@ class OptionInput(InputTypeBase):
"""
Return extra context.
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
return {'default_option_text': _('Select an option')}
#-----------------------------------------------------------------------------
@@ -507,7 +506,7 @@ class ChoiceGroup(InputTypeBase):
self.html_input_type = "checkbox"
self.suffix = '[]'
else:
_ = edx_six.get_gettext(i18n)
_ = i18n.gettext
# Translators: 'ChoiceGroup' is an input type and should not be translated.
msg = _("ChoiceGroup: unexpected tag {tag_name}").format(tag_name=self.tag)
raise Exception(msg)
@@ -543,7 +542,7 @@ class ChoiceGroup(InputTypeBase):
"""
choices = []
_ = edx_six.get_gettext(i18n)
_ = i18n.gettext
for choice in element:
if choice.tag == 'choice':
@@ -740,7 +739,7 @@ class FileSubmission(InputTypeBase):
Do some magic to handle queueing status (render as "queued" instead of "incomplete"),
pull queue_len from the msg field. (TODO: get rid of the queue_len hack).
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
submitted_msg = _("Your files have been submitted. As soon as your submission is"
" graded, this message will be replaced with the grader's feedback.")
self.submitted_msg = submitted_msg
@@ -812,7 +811,7 @@ class CodeInput(InputTypeBase):
def setup(self):
""" setup this input type """
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
submitted_msg = _("Your answer has been submitted. As soon as your submission is"
" graded, this message will be replaced with the grader's feedback.")
self.submitted_msg = submitted_msg
@@ -823,7 +822,7 @@ class CodeInput(InputTypeBase):
"""
Define queue_len, arial_label and code mirror exit message context variables
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
return {
'queue_len': self.queue_len,
'aria_label': _('{programming_language} editor').format(
@@ -853,7 +852,7 @@ class MatlabInput(CodeInput):
"""
Handle matlab-specific parsing
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
submitted_msg = _("Submitted. As soon as a response is returned, "
"this message will be replaced by that feedback.")
@@ -936,7 +935,7 @@ class MatlabInput(CodeInput):
def _extra_context(self):
""" Set up additional context variables"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = 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.
@@ -985,7 +984,7 @@ class MatlabInput(CodeInput):
dict - 'success' - whether or not we successfully queued this submission
- 'message' - message to be rendered in case of error
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = 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')}
@@ -1212,7 +1211,7 @@ class ChemicalEquationInput(InputTypeBase):
}
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
result = {'preview': '',
'error': ''}
try:
@@ -1296,7 +1295,7 @@ class FormulaEquationInput(InputTypeBase):
'request_start' : <time sent with request>
}
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
result = {'preview': '',
'error': ''}
@@ -1681,7 +1680,7 @@ class ChoiceTextGroup(InputTypeBase):
elif self.tag == 'checkboxtextgroup':
self.html_input_type = "checkbox"
else:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
msg = _("{input_type}: unexpected tag {tag_name}").format(
input_type="ChoiceTextGroup", tag_name=self.tag
)
@@ -1760,7 +1759,7 @@ class ChoiceTextGroup(InputTypeBase):
]
"""
_ = edx_six.get_gettext(i18n)
_ = i18n.gettext
choices = []
for choice in element:

View File

@@ -1,18 +1,11 @@
#
# File: courseware/capa/responsetypes.py
#
"""
Problem response evaluation. Handles checking of student responses,
of a variety of types.
Used by capa_problem.py
"""
# standard library imports
import abc
# TODO: Refactor this code and fix this issue.
import inspect
import json
import logging
@@ -46,7 +39,6 @@ from six.moves import map, range, zip
import xmodule.capa.safe_exec as safe_exec
import xmodule.capa.xqueue_interface as xqueue_interface
from openedx.core.djangolib.markup import HTML, Text
from openedx.core.lib import edx_six
from openedx.core.lib.grade_utils import round_away_from_zero
from . import correctmap
@@ -257,7 +249,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
- renderer : procedure which produces HTML given an ElementTree
- response_msg: a message displayed at the end of the Response
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# response_id = problem_id + response index
response_id = self.xml.attrib['id']
@@ -347,7 +339,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
e.g. [{'text': 'a hint', 'trigger':[{'choice': 'choice_0', 'selected': True},
{'choice': 'choice_1', 'selected':True}]}]
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# 1. Establish the hint_texts
# This can lead to early-exit if the hint is blank.
if not hint_log:
@@ -494,7 +486,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
unsafely=self.capa_system.can_execute_unsafe_code(),
)
except Exception as err:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
msg = _('Error {err} in evaluating hint function {hintfn}.').format(err=err, hintfn=hintfn)
sourcenum = getattr(self.xml, 'sourceline', _('(Source code line unavailable)'))
msg += "\n" + _("See XML source line {sourcenum}.").format(sourcenum=sourcenum)
@@ -1189,7 +1181,7 @@ class MultipleChoiceResponse(LoncapaResponse):
Fails with LoncapaProblemError if called on a response that is not masking.
"""
# if not self.has_mask():
# _ = edx_six.get_gettext(self.capa_system.i18n)
# _ = self.capa_system.i18n.gettext
# # Translators: 'unmask_name' is a method name and should not be translated.
# msg = "unmask_name called on response that is not masked"
# raise LoncapaProblemError(msg)
@@ -1220,7 +1212,7 @@ class MultipleChoiceResponse(LoncapaResponse):
if choicegroups:
choicegroup = choicegroups[0]
if choicegroup.get('answer-pool') is not None:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Translators: 'shuffle' and 'answer-pool' are attribute names and should not be translated.
msg = _("Do not use shuffle and answer-pool at the same time")
raise LoncapaProblemError(msg)
@@ -1303,7 +1295,7 @@ class MultipleChoiceResponse(LoncapaResponse):
try:
num_choices = int(num_str)
except ValueError:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Translators: 'answer-pool' is an attribute name and should not be translated.
msg = _("answer-pool value should be an integer")
raise LoncapaProblemError(msg) # lint-amnesty, pylint: disable=raise-missing-from
@@ -1370,7 +1362,7 @@ class MultipleChoiceResponse(LoncapaResponse):
# Or perhaps in the overall author workflow, these errors are unhelpful and
# should all be removed.
if len(correct_choices) < 1 or len(incorrect_choices) < 1:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Translators: 'Choicegroup' is an input type and should not be translated.
msg = _("Choicegroup must include at least 1 correct and 1 incorrect choice")
raise LoncapaProblemError(msg)
@@ -1540,7 +1532,7 @@ class NumericalResponse(LoncapaResponse):
self.correct_answer = answer[0] + self.answer_range[0] + ', ' + self.answer_range[1] + answer[-1]
except Exception:
log.debug("Content error--answer '%s' is not a valid range tolerance answer", answer)
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("There was a problem with the staff answer to this problem.")
)
@@ -1572,7 +1564,7 @@ class NumericalResponse(LoncapaResponse):
correct_ans = evaluator({}, {}, answer)
except Exception:
log.debug("Content error--answer '%s' is not a valid number", answer)
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("There was a problem with the staff answer to this problem.")
)
@@ -1596,7 +1588,7 @@ class NumericalResponse(LoncapaResponse):
student_answer = student_answers[self.answer_id]
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
general_exception = StudentInputError(
_("Could not interpret '{student_answer}' as a number.").format(student_answer=html.escape(student_answer))
)
@@ -1783,7 +1775,7 @@ class NumericalResponse(LoncapaResponse):
return False
def get_answers(self):
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Example: "Answer: Answer_1 or Answer_2 or Answer_3".
separator = Text(' {b_start}{or_separator}{b_end} ').format(
# Translators: Separator used in NumericalResponse to display multiple answers.
@@ -2033,7 +2025,7 @@ class StringResponse(LoncapaResponse):
if not given:
return False
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# backward compatibility, should be removed in future.
if self.backward:
return self.check_string_backward(expected, given)
@@ -2072,7 +2064,7 @@ class StringResponse(LoncapaResponse):
return hints_to_show
def get_answers(self):
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Translators: Separator used in StringResponse to display multiple answers.
# Example: "Answer: Answer_1 or Answer_2 or Answer_3".
separator = HTML(' <b>{}</b> ').format(_('or'))
@@ -2176,7 +2168,7 @@ class CustomResponse(LoncapaResponse):
student_answers is a dict with everything from request.POST, but with the first part
of each key removed (the string before the first "_").
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
log.debug('%s: student_answers=%s', six.text_type(self), student_answers)
@@ -2436,7 +2428,7 @@ class CustomResponse(LoncapaResponse):
# Raise an exception
else:
log.error(traceback.format_exc())
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
raise ResponseError(
_("CustomResponse: check function returned an invalid dictionary!")
)
@@ -2560,7 +2552,7 @@ class SymbolicResponse(CustomResponse):
except Exception as err:
log.error("oops in SymbolicResponse (cfn) error %s", err)
log.error(traceback.format_exc())
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Translators: 'SymbolicResponse' is a problem type and should not be translated.
msg = _("An error occurred with SymbolicResponse. The error was: {error_msg}").format(
error_msg=err,
@@ -2656,12 +2648,12 @@ class CodeResponse(LoncapaResponse):
self.initial_display = find_with_default(
codeparam, 'initial_display', '')
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
self.answer = find_with_default(codeparam, 'answer_display',
_('No answer provided.'))
def get_score(self, student_answers):
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
try:
# Note that submission can be a file
submission = student_answers[self.answer_id]
@@ -2737,7 +2729,7 @@ class CodeResponse(LoncapaResponse):
cmap = CorrectMap()
if error:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = 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)
@@ -2757,7 +2749,7 @@ class CodeResponse(LoncapaResponse):
"""Updates the user's score based on the returned message from the grader."""
(valid_score_msg, correct, points, msg) = self._parse_score_msg(score_msg)
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
if not valid_score_msg:
# Translators: 'grader' refers to the edX automatic code grader.
@@ -3091,7 +3083,7 @@ class FormulaResponse(LoncapaResponse):
Each dictionary represents a test case for the answer.
Returns a tuple of formula evaluation results.
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
out = []
for var_dict in var_dict_list:
@@ -3288,7 +3280,7 @@ class SchematicResponse(LoncapaResponse):
unsafely=self.capa_system.can_execute_unsafe_code(),
)
except Exception as err:
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
# Translators: 'SchematicResponse' is a problem type and should not be translated.
msg = _('Error in evaluating SchematicResponse. The error was: {error_msg}').format(error_msg=err)
raise ResponseError(msg) # lint-amnesty, pylint: disable=raise-missing-from
@@ -3344,7 +3336,7 @@ class ImageResponse(LoncapaResponse):
self.answer_ids = [ie.get('id') for ie in self.ielements]
def get_score(self, student_answers):
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
correct_map = CorrectMap()
expectedset = self.get_mapped_answers()
for aid in self.answer_ids: # loop through IDs of <imageinput>
@@ -3606,7 +3598,7 @@ class ChoiceTextResponse(LoncapaResponse):
and `answer_values` is used for displaying correct answers.
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
context = self.context
self.answer_values = {self.answer_id: []}
self.assign_choice_names()
@@ -3854,7 +3846,7 @@ class ChoiceTextResponse(LoncapaResponse):
Returns True if and only if all student inputs are correct.
"""
_ = edx_six.get_gettext(self.capa_system.i18n)
_ = self.capa_system.i18n.gettext
inputs_correct = True
for answer_name, answer_value in six.iteritems(numtolerance_inputs):
# If `self.corrrect_inputs` does not contain an entry for