Applied pylint-amnesty

This commit is contained in:
usamasadiq
2021-02-04 16:55:33 +05:00
parent 87a3777a79
commit bbc386752f
175 changed files with 1396 additions and 1395 deletions

View File

@@ -435,7 +435,7 @@ class LoncapaProblem(object):
# if answers include File objects, convert them to filenames.
self.student_answers = convert_files_to_filenames(answers)
new_cmap = self.get_grade_from_current_answers(answers)
self.correct_map = new_cmap
self.correct_map = new_cmap # lint-amnesty, pylint: disable=attribute-defined-outside-init
return self.correct_map
def supports_rescoring(self):
@@ -506,7 +506,7 @@ class LoncapaProblem(object):
"""
# dict of (id, correct_answer)
answer_map = dict()
for response in self.responders.keys():
for response in self.responders.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
results = self.responder_answers[response]
answer_map.update(results)
@@ -526,7 +526,7 @@ class LoncapaProblem(object):
get_question_answers may only return a subset of these.
"""
answer_ids = []
for response in self.responders.keys():
for response in self.responders.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
results = self.responder_answers[response]
answer_ids.append(list(results.keys()))
return answer_ids
@@ -809,7 +809,7 @@ class LoncapaProblem(object):
try:
# open using LoncapaSystem OSFS filestore
ifp = self.capa_system.filestore.open(filename)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
log.warning(
'Error %s in problem xml include: %s',
err,
@@ -820,14 +820,14 @@ class LoncapaProblem(object):
)
# if debugging, don't fail - just log error
# TODO (vshnayder): need real error handling, display to users
if not self.capa_system.DEBUG:
if not self.capa_system.DEBUG: # lint-amnesty, pylint: disable=no-else-raise
raise
else:
continue
try:
# read in and convert to XML
incxml = etree.XML(ifp.read())
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
log.warning(
'Error %s in problem xml include: %s',
err,
@@ -836,7 +836,7 @@ class LoncapaProblem(object):
log.warning('Cannot parse XML in %s', (filename))
# if debugging, don't fail - just log error
# TODO (vshnayder): same as above
if not self.capa_system.DEBUG:
if not self.capa_system.DEBUG: # lint-amnesty, pylint: disable=no-else-raise
raise
else:
continue
@@ -864,7 +864,7 @@ class LoncapaProblem(object):
# find additional comma-separated modules search path
path = []
for dir in raw_path:
for dir in raw_path: # lint-amnesty, pylint: disable=redefined-builtin
if not dir:
continue
@@ -937,7 +937,7 @@ class LoncapaProblem(object):
unsafely=self.capa_system.can_execute_unsafe_code(),
)
except Exception as err:
log.exception("Error while execing script code: " + all_code)
log.exception("Error while execing script code: " + all_code) # lint-amnesty, pylint: disable=logging-not-lazy
msg = Text("Error while executing script code: %s" % str(err))
raise responsetypes.LoncapaProblemError(msg)
@@ -1111,7 +1111,7 @@ class LoncapaProblem(object):
# get responder answers (do this only once, since there may be a performance cost,
# eg with externalresponse)
self.responder_answers = {}
for response in self.responders.keys():
for response in self.responders.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
try:
self.responder_answers[response] = self.responders[response].get_answers()
except:

View File

@@ -19,7 +19,7 @@ logging.basicConfig(format="%(levelname)s %(message)s")
log = logging.getLogger('capa.checker')
class DemoSystem(object):
class DemoSystem(object): # lint-amnesty, pylint: disable=missing-class-docstring
def __init__(self):
self.lookup = TemplateLookup(directories=[path(__file__).dirname() / 'templates'])
self.DEBUG = True
@@ -31,7 +31,7 @@ class DemoSystem(object):
return self.lookup.get_template(template_filename).render(**dictionary)
def main():
def main(): # lint-amnesty, pylint: disable=missing-function-docstring
parser = argparse.ArgumentParser(description='Check Problem Files')
parser.add_argument("command", choices=['test', 'show']) # Watch? Render? Open?
parser.add_argument("files", nargs="+", type=argparse.FileType('r'))
@@ -49,8 +49,8 @@ def main():
log.info("Opening {0}".format(problem_file.name))
try:
problem = LoncapaProblem(problem_file, "fakeid", seed=args.seed, system=system)
except Exception as ex:
problem = LoncapaProblem(problem_file, "fakeid", seed=args.seed, system=system) # lint-amnesty, pylint: disable=no-value-for-parameter, unexpected-keyword-arg
except Exception as ex: # lint-amnesty, pylint: disable=broad-except
log.error("Could not parse file {0}".format(problem_file.name))
log.exception(ex)
continue
@@ -70,7 +70,7 @@ def command_show(problem):
print(problem.get_html())
def command_test(problem):
def command_test(problem): # lint-amnesty, pylint: disable=missing-function-docstring
# We're going to trap stdout/stderr from the problems (yes, some print)
old_stdout, old_stderr = sys.stdout, sys.stderr
try:
@@ -84,7 +84,7 @@ def command_test(problem):
"captured stdout from {0}".format(problem))
log_captured_output(sys.stderr,
"captured stderr from {0}".format(problem))
except Exception as e:
except Exception as e: # lint-amnesty, pylint: disable=broad-except
log.exception(e)
finally:
sys.stdout, sys.stderr = old_stdout, old_stderr
@@ -135,7 +135,7 @@ def check_that_suggested_answers_work(problem):
assert(all(result == 'correct'
for answer_id, result in real_results.items()))
except UndefinedVariable as uv_exc:
log.error("The variable \"{0}\" specified in the ".format(uv_exc) +
log.error("The variable \"{0}\" specified in the ".format(uv_exc) + # lint-amnesty, pylint: disable=logging-not-lazy
"solution isn't recognized (is it a units measure?).")
except AssertionError:
log.error("The following generated answers were not accepted for {0}:"
@@ -143,16 +143,16 @@ def check_that_suggested_answers_work(problem):
for question_id, result in sorted(real_results.items()):
if result != 'correct':
log.error(" {0} = {1}".format(question_id, real_answers[question_id]))
except Exception as ex:
except Exception as ex: # lint-amnesty, pylint: disable=broad-except
log.error("Uncaught error in {0}".format(problem))
log.exception(ex)
def log_captured_output(output_stream, stream_name):
def log_captured_output(output_stream, stream_name): # lint-amnesty, pylint: disable=missing-function-docstring
output_stream.seek(0)
output_text = output_stream.read()
if output_text:
log.info("##### Begin {0} #####\n".format(stream_name) + output_text)
log.info("##### Begin {0} #####\n".format(stream_name) + output_text) # lint-amnesty, pylint: disable=logging-not-lazy
log.info("##### End {0} #####".format(stream_name))

View File

@@ -1,4 +1,4 @@
# -----------------------------------------------------------------------------
# ----------------------------------------------------------------------------- # lint-amnesty, pylint: disable=missing-module-docstring
# class used to store graded responses to CAPA questions
#
# Used by responsetypes and capa_problem
@@ -38,8 +38,8 @@ class CorrectMap(object):
return self.cmap.__iter__()
# See the documentation for 'set_dict' for the use of kwargs
def set(
self,
def set( # lint-amnesty, pylint: disable=missing-function-docstring
self, # lint-amnesty, pylint: disable=unused-argument
answer_id=None,
correctness=None,
npoints=None,
@@ -47,7 +47,7 @@ class CorrectMap(object):
hint='',
hintmode=None,
queuestate=None,
answervariable=None, # pylint: disable=C0330
answervariable=None, # lint-amnesty, pylint: disable=C0330, bad-option-value
**kwargs
):
@@ -144,13 +144,13 @@ class CorrectMap(object):
# if not correct and no points have been assigned, return 0
return 0
def set_property(self, answer_id, property, value):
def set_property(self, answer_id, property, value): # lint-amnesty, pylint: disable=redefined-builtin
if answer_id in self.cmap:
self.cmap[answer_id][property] = value
else:
self.cmap[answer_id] = {property: value}
def get_property(self, answer_id, property, default=None):
def get_property(self, answer_id, property, default=None): # lint-amnesty, pylint: disable=redefined-builtin
if answer_id in self.cmap:
return self.cmap[answer_id].get(property, default)
return default

View File

@@ -24,7 +24,7 @@ registry = TagRegistry()
# -----------------------------------------------------------------------------
class MathRenderer(object):
class MathRenderer(object): # lint-amnesty, pylint: disable=missing-class-docstring
tags = ['math']
def __init__(self, system, xml):
@@ -57,11 +57,11 @@ class MathRenderer(object):
"""
# TODO: why are there nested html tags here?? Why are there html tags at all, in fact?
# xss-lint: disable=python-interpolate-html
html = '<html><html>%s</html><html>%s</html></html>' % (
html = '<html><html>%s</html><html>%s</html></html>' % ( # lint-amnesty, pylint: disable=redefined-outer-name
self.mathstr, saxutils.escape(self.xml.tail))
try:
xhtml = etree.XML(html)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
if self.system.DEBUG:
# xss-lint: disable=python-interpolate-html
msg = '<html><div class="inline-error"><p>Error %s</p>' % (
@@ -99,7 +99,7 @@ class SolutionRenderer(object):
def get_html(self):
context = {'id': self.id}
html = self.system.render_template("solutionspan.html", context)
html = self.system.render_template("solutionspan.html", context) # lint-amnesty, pylint: disable=redefined-outer-name
return etree.XML(html)
@@ -175,7 +175,7 @@ class ClarificationRenderer(object):
Return the contents of this tag, rendered to html, as an etree element.
"""
context = {'clarification': self.inner_html}
html = self.system.render_template("clarification.html", context)
html = self.system.render_template("clarification.html", context) # lint-amnesty, pylint: disable=redefined-outer-name
xml = etree.XML(html)
# We must include any text that was following our original <clarification>...</clarification> XML node.:
xml.tail = self.tail

View File

@@ -254,7 +254,7 @@ class InputTypeBase(object):
# super().__init__, and are isolated from changes to the input
# constructor interface.
self.setup()
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
# Something went wrong: add xml to message, but keep the traceback
msg = u"Error in xml '{x}': {err} ".format(
x=etree.tostring(xml), err=text_type(err))
@@ -298,7 +298,7 @@ class InputTypeBase(object):
If this method raises an exception, it will be wrapped with a message that includes the
problem xml.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def handle_ajax(self, dispatch, data):
"""
@@ -311,7 +311,7 @@ class InputTypeBase(object):
Output:
a dictionary object that can be serialized into JSON. This will be sent back to the Javascript.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def _get_render_context(self):
"""
@@ -384,11 +384,11 @@ class InputTypeBase(object):
output = etree.XML(html)
except etree.XMLSyntaxError as ex:
# If `html` contains attrs with no values, like `controls` in <audio controls src='smth'/>,
# XML parser will raise exception, so wee fallback to html5parser, which will set empty "" values for such attrs.
# XML parser will raise exception, so wee fallback to html5parser, which will set empty "" values for such attrs. # lint-amnesty, pylint: disable=line-too-long
try:
output = html5lib.parseFragment(html, treebuilder='lxml', namespaceHTMLElements=False)[0]
except IndexError:
raise ex
raise ex # lint-amnesty, pylint: disable=raise-missing-from
return output
@@ -802,12 +802,12 @@ class CodeInput(InputTypeBase):
self.value = self.xml.text.strip()
# Check if problem has been queued
self.queue_len = 0
self.queue_len = 0 # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Flag indicating that the problem has been queued, 'msg' is length of
# queue
if self.status == 'incomplete':
self.status = 'queued'
self.queue_len = self.msg
self.queue_len = self.msg # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.msg = bleach.clean(self.submitted_msg)
def setup(self):
@@ -908,7 +908,7 @@ class MatlabInput(CodeInput):
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
- queuekey (str) - a key passed to the queue. Will be matched up to verify that this is the response we're waiting for # lint-amnesty, pylint: disable=line-too-long
Returns:
nothing
@@ -1225,7 +1225,7 @@ class ChemicalEquationInput(InputTypeBase):
result['preview'] = chemcalc.render_to_html(formula)
except pyparsing.ParseException as err:
result['error'] = _("Couldn't parse formula: {error_msg}").format(error_msg=err.msg)
except Exception:
except Exception: # lint-amnesty, pylint: disable=broad-except
# this is unexpected, so log
log.warning(
"Error while previewing chemical formula", exc_info=True)
@@ -1275,7 +1275,7 @@ class FormulaEquationInput(InputTypeBase):
static_url=self.capa_system.STATIC_URL),
}
def handle_ajax(self, dispatch, get):
def handle_ajax(self, dispatch, get): # lint-amnesty, pylint: disable=arguments-differ
"""
Since we only have formcalc preview this input, check to see if it
matches the corresponding dispatch and send it through if it does
@@ -1316,7 +1316,7 @@ class FormulaEquationInput(InputTypeBase):
except pyparsing.ParseException:
result['error'] = _("Sorry, couldn't parse formula")
result['formula'] = formula
except Exception:
except Exception: # lint-amnesty, pylint: disable=broad-except
# this is unexpected, so log
log.warning(
"Error while previewing formula", exc_info=True
@@ -1364,17 +1364,17 @@ class DragAndDropInput(InputTypeBase):
"""
tag_attrs = dict()
tag_attrs['draggable'] = {
'id': Attribute._sentinel,
'id': Attribute._sentinel, # lint-amnesty, pylint: disable=protected-access
'label': "", 'icon': "",
'can_reuse': ""
}
tag_attrs['target'] = {
'id': Attribute._sentinel,
'x': Attribute._sentinel,
'y': Attribute._sentinel,
'w': Attribute._sentinel,
'h': Attribute._sentinel
'id': Attribute._sentinel, # lint-amnesty, pylint: disable=protected-access
'x': Attribute._sentinel, # lint-amnesty, pylint: disable=protected-access
'y': Attribute._sentinel, # lint-amnesty, pylint: disable=protected-access
'w': Attribute._sentinel, # lint-amnesty, pylint: disable=protected-access
'h': Attribute._sentinel # lint-amnesty, pylint: disable=protected-access
}
dic = dict()
@@ -1542,7 +1542,7 @@ class AnnotationInput(InputTypeBase):
They are the ones who, at the public assembly, had put savage derangement [ate] into my thinking
[phrenes] |89 on that day when I myself deprived Achilles of his honorific portion [geras]
</text>
<comment>Agamemnon says that ate or 'derangement' was the cause of his actions: why could Zeus say the same thing?</comment>
<comment>Agamemnon says that ate or 'derangement' was the cause of his actions: why could Zeus say the same thing?</comment> # lint-amnesty, pylint: disable=line-too-long
<comment_prompt>Type a commentary below:</comment_prompt>
<tag_prompt>Select one tag:</tag_prompt>
<options>
@@ -1593,7 +1593,7 @@ class AnnotationInput(InputTypeBase):
valid_choices = ('correct', 'partially-correct', 'incorrect')
for option in self.options:
choice = option['choice']
if choice is None:
if choice is None: # lint-amnesty, pylint: disable=no-else-raise
raise ValueError('Missing required choice attribute.')
elif choice not in valid_choices:
raise ValueError('Invalid choice attribute: {0}. Must be one of: {1}'.format(

View File

@@ -87,7 +87,7 @@ class LoncapaProblemError(Exception):
"""
Error in specification of a problem
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class ResponseError(Exception):
@@ -95,7 +95,7 @@ class ResponseError(Exception):
Error for failure in processing a response, including
exceptions that occur when executing a custom script.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class StudentInputError(Exception):
@@ -103,7 +103,7 @@ class StudentInputError(Exception):
Error for an invalid student input.
For example, submitting a string when the problem expects a number
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
#-----------------------------------------------------------------------------
#
@@ -426,7 +426,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
installing it in the new_map for display.
Implemented by subclasses that have extended hints.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def get_hints(self, student_answers, new_cmap, old_cmap):
"""
@@ -500,7 +500,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
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)
raise ResponseError(msg)
raise ResponseError(msg) # lint-amnesty, pylint: disable=raise-missing-from
new_cmap.set_dict(globals_dict['new_cmap_dict'])
return
@@ -528,7 +528,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
and hasattr(self, 'check_hint_condition')):
rephints = hintgroup.findall(self.hint_tag)
hints_to_show = self.check_hint_condition(
hints_to_show = self.check_hint_condition( # lint-amnesty, pylint: disable=assignment-from-no-return
rephints, student_answers)
# can be 'on_request' or 'always' (default)
@@ -554,14 +554,14 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
Arguments:
- student_answers : dict of (answer_id, answer) where answer = student input (string)
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abc.abstractmethod
def get_answers(self):
"""
Return a dict of (answer_id, answer_text) for each answer for this question.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def check_hint_condition(self, hxml_set, student_answers):
"""
@@ -575,7 +575,7 @@ class LoncapaResponse(six.with_metaclass(abc.ABCMeta, object)):
Returns a list of names of hint conditions which were satisfied. Those are used
to determine which hints are displayed.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def setup_response(self):
pass
@@ -1037,7 +1037,7 @@ class MultipleChoiceResponse(LoncapaResponse):
if contextualize_text(choice.get('correct'), self.context).lower() == 'partial'
]
def get_extended_hints(self, student_answer_dict, new_cmap):
def get_extended_hints(self, student_answer_dict, new_cmap): # lint-amnesty, pylint: disable=arguments-differ
"""
Extract any hints in a <choicegroup> matching the student's answers
<choicegroup label="What is your favorite color?" type="MultipleChoice">
@@ -1308,7 +1308,7 @@ class MultipleChoiceResponse(LoncapaResponse):
_ = edx_six.get_gettext(self.capa_system.i18n)
# Translators: 'answer-pool' is an attribute name and should not be translated.
msg = _("answer-pool value should be an integer")
raise LoncapaProblemError(msg)
raise LoncapaProblemError(msg) # lint-amnesty, pylint: disable=raise-missing-from
# Note in the response that answerpool is done.
# Both to avoid double-processing, and to feed the logs.
@@ -1396,7 +1396,7 @@ class MultipleChoiceResponse(LoncapaResponse):
@registry.register
class TrueFalseResponse(MultipleChoiceResponse):
class TrueFalseResponse(MultipleChoiceResponse): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring
human_name = _('True/False Choice')
tags = ['truefalseresponse']
@@ -1456,7 +1456,7 @@ class OptionResponse(LoncapaResponse):
return cmap
def get_answers(self):
amap = dict([(af.get('id'), contextualize_text(af.get(
amap = dict([(af.get('id'), contextualize_text(af.get( # lint-amnesty, pylint: disable=consider-using-dict-comprehension
'correct'), self.context)) for af in self.answer_fields])
return amap
@@ -1521,7 +1521,7 @@ class NumericalResponse(LoncapaResponse):
self.tolerance = default_tolerance
self.range_tolerance = False
self.answer_range = self.inclusion = None
super(NumericalResponse, self).__init__(*args, **kwargs)
super(NumericalResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
xml = self.xml
@@ -1535,7 +1535,7 @@ class NumericalResponse(LoncapaResponse):
if answer.startswith(('[', '(')) and answer.endswith((']', ')')): # range tolerance case
self.range_tolerance = True
self.inclusion = (
True if answer.startswith('[') else False, True if answer.endswith(']') else False
True if answer.startswith('[') else False, True if answer.endswith(']') else False # lint-amnesty, pylint: disable=simplifiable-if-expression
)
try:
self.answer_range = [contextualize_text(x, context) for x in answer[1:-1].split(',')]
@@ -1543,7 +1543,7 @@ class NumericalResponse(LoncapaResponse):
except Exception:
log.debug("Content error--answer '%s' is not a valid range tolerance answer", answer)
_ = edx_six.get_gettext(self.capa_system.i18n)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("There was a problem with the staff answer to this problem.")
)
else:
@@ -1575,13 +1575,13 @@ class NumericalResponse(LoncapaResponse):
except Exception:
log.debug("Content error--answer '%s' is not a valid number", answer)
_ = edx_six.get_gettext(self.capa_system.i18n)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("There was a problem with the staff answer to this problem.")
)
return correct_ans
def get_score(self, student_answers):
def get_score(self, student_answers): # lint-amnesty, pylint: disable=too-many-statements
"""
Grade a numeric response.
"""
@@ -1608,31 +1608,31 @@ class NumericalResponse(LoncapaResponse):
try:
student_float = evaluator({}, {}, student_answer)
except UndefinedVariable as err:
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
err.args[0]
)
except UnmatchedParenthesis as err:
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
err.args[0]
)
except ValueError as val_err:
if 'factorial' in text_type(val_err):
if 'factorial' in text_type(val_err): # lint-amnesty, pylint: disable=no-else-raise
# This is thrown when fact() or factorial() is used in an answer
# that evaluates on negative and/or non-integer inputs
# text_type(ve) will be: `factorial() only accepts integral values` or
# `factorial() not defined for negative values`
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("Factorial function evaluated outside its domain:"
"'{student_answer}'").format(student_answer=html.escape(student_answer))
)
else:
raise general_exception
raise general_exception # lint-amnesty, pylint: disable=raise-missing-from
except ParseException:
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_(u"Invalid math syntax: '{student_answer}'").format(student_answer=html.escape(student_answer))
)
except Exception:
raise general_exception
raise general_exception # lint-amnesty, pylint: disable=raise-missing-from
# End `evaluator` block -- we figured out the student's answer!
tree = self.xml
@@ -2052,7 +2052,7 @@ class StringResponse(LoncapaResponse):
message=text_type(err)
)
log.error(msg, exc_info=True)
raise ResponseError(msg)
raise ResponseError(msg) # lint-amnesty, pylint: disable=raise-missing-from
return bool(result)
else: # string match
if self.case_insensitive:
@@ -2205,7 +2205,7 @@ class CustomResponse(LoncapaResponse):
"\n idset = %s, error = %s",
student_answers, idset, err
)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
# global variable in context which holds the Presentation MathML from dynamic math input
# ordered list of dynamath responses
@@ -2277,7 +2277,7 @@ class CustomResponse(LoncapaResponse):
correct_map = CorrectMap()
correct_map.set_overall_message(overall_message)
for k in range(len(idset)):
for k in range(len(idset)): # lint-amnesty, pylint: disable=consider-using-enumerate
max_points = self.maxpoints[idset[k]]
if grade_decimals:
npoints = max_points * grade_decimals[k]
@@ -2292,9 +2292,9 @@ class CustomResponse(LoncapaResponse):
npoints=npoints)
return correct_map
def execute_check_function(self, idset, submission):
def execute_check_function(self, idset, submission): # lint-amnesty, pylint: disable=missing-function-docstring, too-many-statements
# exec the check function
if isinstance(self.code, six.string_types):
if isinstance(self.code, six.string_types): # lint-amnesty, pylint: disable=too-many-nested-blocks
try:
safe_exec.safe_exec(
self.code,
@@ -2462,7 +2462,7 @@ class CustomResponse(LoncapaResponse):
self.context['correct'] = correct
def clean_message_html(self, msg):
def clean_message_html(self, msg): # lint-amnesty, pylint: disable=missing-function-docstring
# If *msg* is an empty string, then the code below
# will return "</html>". To avoid this, we first check
@@ -2544,7 +2544,7 @@ class SymbolicResponse(CustomResponse):
self.xml.set('cfn', 'symmath_check')
# Let CustomResponse do its setup
super(SymbolicResponse, self).setup_response()
super(SymbolicResponse, self).setup_response() # lint-amnesty, pylint: disable=super-with-arguments
def execute_check_function(self, idset, submission):
from symmath import symmath_check
@@ -2567,7 +2567,7 @@ class SymbolicResponse(CustomResponse):
msg = _(u"An error occurred with SymbolicResponse. The error was: {error_msg}").format(
error_msg=err,
)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
self.context['messages'][0] = self.clean_message_html(ret['msg'])
self.context['correct'] = ['correct' if ret['ok'] else 'incorrect'] * len(idset)
@@ -2673,7 +2673,7 @@ class CodeResponse(LoncapaResponse):
' student_answers=%s',
err, self.answer_id, convert_files_to_filenames(student_answers)
)
raise Exception(err)
raise Exception(err) # lint-amnesty, pylint: disable=raise-missing-from
# We do not support xqueue within Studio.
if self.capa_system.xqueue is None:
@@ -2888,7 +2888,7 @@ class ExternalResponse(LoncapaResponse):
self.url = ''
self.tests = []
self.code = ''
super(ExternalResponse, self).__init__(*args, **kwargs)
super(ExternalResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
xml = self.xml
@@ -2940,7 +2940,7 @@ class ExternalResponse(LoncapaResponse):
except Exception as err:
msg = 'Error {0} - cannot connect to external server url={1}'.format(err, self.url)
log.error(msg)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
if self.capa_system.DEBUG:
log.info('response = %s', req.text)
@@ -2955,7 +2955,7 @@ class ExternalResponse(LoncapaResponse):
except Exception as err:
msg = 'Error {0} - cannot parse response from external server req.text={1}'.format(err, req.text)
log.error(msg)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
return rxml
@@ -2971,7 +2971,7 @@ class ExternalResponse(LoncapaResponse):
self.answer_ids,
student_answers
)
raise Exception(err)
raise Exception(err) # lint-amnesty, pylint: disable=raise-missing-from
self.context.update({'submission': submission})
@@ -3047,7 +3047,7 @@ class FormulaResponse(LoncapaResponse):
self.samples = ''
self.tolerance = default_tolerance
self.case_sensitive = False
super(FormulaResponse, self).__init__(*args, **kwargs)
super(FormulaResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
xml = self.xml
@@ -3109,7 +3109,7 @@ class FormulaResponse(LoncapaResponse):
'formularesponse: undefined variable in formula=%s',
html.escape(answer)
)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
err.args[0]
)
except UnmatchedParenthesis as err:
@@ -3117,7 +3117,7 @@ class FormulaResponse(LoncapaResponse):
'formularesponse: unmatched parenthesis in formula=%s',
html.escape(answer)
)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
err.args[0]
)
except ValueError as err:
@@ -3132,14 +3132,14 @@ class FormulaResponse(LoncapaResponse):
'Provided answer was: %s'),
html.escape(answer)
)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("Factorial function not permitted in answer "
"for this problem. Provided answer was: "
"{bad_input}").format(bad_input=html.escape(answer))
)
# If non-factorial related ValueError thrown, handle it the same as any other Exception
log.debug('formularesponse: error %s in formula', err)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("Invalid input: Could not parse '{bad_input}' as a formula.").format(
bad_input=html.escape(answer)
)
@@ -3147,7 +3147,7 @@ class FormulaResponse(LoncapaResponse):
except Exception as err:
# traceback.print_exc()
log.debug('formularesponse: error %s in formula', err)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("Invalid input: Could not parse '{bad_input}' as a formula").format(
bad_input=html.escape(answer)
)
@@ -3216,7 +3216,7 @@ class FormulaResponse(LoncapaResponse):
keys and all non-numeric values stripped out. All values also
converted to float. Used so we can safely use Python contexts.
"""
inp_d = dict([(k, numpy.complex(inp_d[k]))
inp_d = dict([(k, numpy.complex(inp_d[k])) # lint-amnesty, pylint: disable=consider-using-dict-comprehension
for k in inp_d if isinstance(k, str) and
k.isalnum() and
isinstance(inp_d[k], numbers.Number)])
@@ -3261,7 +3261,7 @@ class SchematicResponse(LoncapaResponse):
def __init__(self, *args, **kwargs):
self.code = ''
super(SchematicResponse, self).__init__(*args, **kwargs)
super(SchematicResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
xml = self.xml
@@ -3293,7 +3293,7 @@ class SchematicResponse(LoncapaResponse):
_ = edx_six.get_gettext(self.capa_system.i18n)
# 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)
raise ResponseError(msg) # lint-amnesty, pylint: disable=raise-missing-from
cmap = CorrectMap()
cmap.set_dict(dict(list(zip(sorted(self.answer_ids), self.context['correct']))))
return cmap
@@ -3339,7 +3339,7 @@ class ImageResponse(LoncapaResponse):
def __init__(self, *args, **kwargs):
self.ielements = []
super(ImageResponse, self).__init__(*args, **kwargs)
super(ImageResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
self.ielements = self.inputfields
@@ -3419,9 +3419,9 @@ class ImageResponse(LoncapaResponse):
regions (dict) - a map of inputs to the defined region for that input
"""
answers = (
dict([(ie.get('id'), ie.get(
dict([(ie.get('id'), ie.get( # lint-amnesty, pylint: disable=consider-using-dict-comprehension
'rectangle')) for ie in self.ielements]),
dict([(ie.get('id'), ie.get('regions')) for ie in self.ielements]))
dict([(ie.get('id'), ie.get('regions')) for ie in self.ielements])) # lint-amnesty, pylint: disable=consider-using-dict-comprehension
return answers
def get_answers(self):
@@ -3461,7 +3461,7 @@ class AnnotationResponse(LoncapaResponse):
def __init__(self, *args, **kwargs):
self.scoring_map = {}
self.answer_map = {}
super(AnnotationResponse, self).__init__(*args, **kwargs)
super(AnnotationResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
self.scoring_map = self._get_scoring_map()
@@ -3493,11 +3493,11 @@ class AnnotationResponse(LoncapaResponse):
def _get_scoring_map(self):
"""Returns a dict of option->scoring for each input."""
scoring = self.default_scoring
choices = dict([(choice, choice) for choice in scoring])
choices = dict([(choice, choice) for choice in scoring]) # lint-amnesty, pylint: disable=consider-using-dict-comprehension
scoring_map = {}
for inputfield in self.inputfields:
option_scoring = dict([(
option_scoring = dict([( # lint-amnesty, pylint: disable=consider-using-dict-comprehension
option['id'],
{
'correctness': choices.get(option['choice']),
@@ -3524,7 +3524,7 @@ class AnnotationResponse(LoncapaResponse):
"""Returns a dict of the max points for each input: input id -> maxpoints."""
scoring = self.default_scoring
correct_points = scoring.get('correct')
return dict([(inputfield.get('id'), correct_points) for inputfield in self.inputfields])
return dict([(inputfield.get('id'), correct_points) for inputfield in self.inputfields]) # lint-amnesty, pylint: disable=consider-using-dict-comprehension
def _find_options(self, inputfield):
"""Returns an array of dicts where each dict represents an option. """
@@ -3592,7 +3592,7 @@ class ChoiceTextResponse(LoncapaResponse):
self.correct_inputs = {}
self.answer_values = {}
self.correct_choices = {}
super(ChoiceTextResponse, self).__init__(*args, **kwargs)
super(ChoiceTextResponse, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def setup_response(self):
"""
@@ -3877,7 +3877,7 @@ class ChoiceTextResponse(LoncapaResponse):
"Content error--answer '%s' is not a valid complex number",
correct_ans
)
raise StudentInputError(
raise StudentInputError( # lint-amnesty, pylint: disable=raise-missing-from
_("The Staff answer could not be interpreted as a number.")
)
# Compare the student answer to the staff answer/ or to 0
@@ -3896,7 +3896,7 @@ class ChoiceTextResponse(LoncapaResponse):
given_answer=html.escape(answer_value)
)
msg += " ({0})".format(trace)
raise StudentInputError(msg)
raise StudentInputError(msg) # lint-amnesty, pylint: disable=raise-missing-from
# Ignore the results of the comparisons which were just for
# Numerical Validation.

View File

@@ -36,8 +36,8 @@ class LazyModule(object):
try:
subname = '%s.%s' % (self.__name__, name)
__import__(subname)
submod = getattr(mod, name)
submod = getattr(mod, name) # lint-amnesty, pylint: disable=unused-variable
except ImportError:
raise AttributeError("'module' object has no attribute %r" % name)
raise AttributeError("'module' object has no attribute %r" % name) # lint-amnesty, pylint: disable=raise-missing-from
self.__dict__[name] = LazyModule(subname)
return self.__dict__[name]

View File

@@ -18,7 +18,7 @@ class ModuleIsolation(object):
# Save all the names of all the imported modules.
self.mods = set(sys.modules)
def clean_up(self):
def clean_up(self): # lint-amnesty, pylint: disable=missing-function-docstring
# Get a list of modules that didn't exist when we were created
new_mods = [m for m in sys.modules if m not in self.mods]
# and delete them all so another import will run code for real again.
@@ -26,10 +26,10 @@ class ModuleIsolation(object):
del sys.modules[m]
class TestLazyMod(unittest.TestCase):
class TestLazyMod(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def setUp(self):
super(TestLazyMod, self).setUp()
super(TestLazyMod, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
# Each test will remove modules that it imported.
self.addCleanup(ModuleIsolation().clean_up)

View File

@@ -22,7 +22,7 @@ from six.moves import range
from capa.safe_exec import safe_exec, update_hash
class TestSafeExec(unittest.TestCase):
class TestSafeExec(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_set_values(self):
g = {}
safe_exec("a = 17", g)
@@ -80,7 +80,7 @@ class TestSafeExec(unittest.TestCase):
self.assertIn("ZeroDivisionError", text_type(cm.exception))
class TestSafeOrNot(unittest.TestCase):
class TestSafeOrNot(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_cant_do_something_forbidden(self):
# Can't test for forbiddenness if CodeJail isn't configured for python.
if not jail_code.is_configured("python"):
@@ -231,7 +231,7 @@ class TestSafeExecCaching(unittest.TestCase):
# The exception should be in the cache now.
self.assertEqual(len(cache), 1)
cache_exc_msg, cache_globals = list(cache.values())[0]
cache_exc_msg, cache_globals = list(cache.values())[0] # lint-amnesty, pylint: disable=unused-variable
self.assertIn("ZeroDivisionError", cache_exc_msg)
# Change the value stored in the cache, the result should change.
@@ -321,7 +321,7 @@ class TestUpdateHash(unittest.TestCase):
self.assertEqual(h1, h2)
class TestRealProblems(unittest.TestCase):
class TestRealProblems(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_802x(self):
code = textwrap.dedent("""\
import math

View File

@@ -86,7 +86,7 @@ def mock_capa_module():
"""
capa response types needs just two things from the capa_module: location and track_function.
"""
def mock_location_text(self):
def mock_location_text(self): # lint-amnesty, pylint: disable=unused-argument
"""
Mock implementation of __unicode__ or __str__ for the module's location.
"""

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from abc import ABCMeta, abstractmethod
@@ -372,7 +372,7 @@ class CodeResponseXMLFactory(ResponseXMLFactory):
# we should override the default behavior
# of including a <solution> tag as well
kwargs['explanation_text'] = None
return super(CodeResponseXMLFactory, self).build_xml(**kwargs)
return super(CodeResponseXMLFactory, self).build_xml(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def create_response_element(self, **kwargs):
"""
@@ -536,7 +536,7 @@ class FormulaResponseXMLFactory(ResponseXMLFactory):
def create_input_element(self, **kwargs):
return ResponseXMLFactory.textline_input_xml(**kwargs)
def _sample_str(self, sample_dict, num_samples, tolerance):
def _sample_str(self, sample_dict, num_samples, tolerance): # lint-amnesty, pylint: disable=missing-function-docstring, unused-argument
# Loncapa uses a special format for sample strings:
# "x,y,z@4,5,3:10,12,8#4" means plug in values for (x,y,z)
# from within the box defined by points (4,5,3) and (10,12,8)

View File

@@ -14,7 +14,7 @@ from capa.tests.helpers import new_loncapa_problem, test_capa_system
class CapaAnswerPoolTest(unittest.TestCase):
"""Capa Answer Pool Test"""
def setUp(self):
super(CapaAnswerPoolTest, self).setUp()
super(CapaAnswerPoolTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.system = test_capa_system()
# XML problem setup used by a few tests.
@@ -115,7 +115,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
problem = new_loncapa_problem(xml_str)
the_html = problem.get_html()
self.assertRegex(the_html, r"<div>.*\[.*'wrong-1'.*'wrong-2'.*'correct-1'.*'wrong-3'.*'wrong-4'.*'correct-2'.*\].*</div>")
self.assertRegex(the_html, r"<div>.*\[.*'wrong-1'.*'wrong-2'.*'correct-1'.*'wrong-3'.*'wrong-4'.*'correct-2'.*\].*</div>") # lint-amnesty, pylint: disable=line-too-long
self.assertRegex(the_html, r"<div>\{.*'1_solution_1'.*'1_solution_2'.*\}</div>")
self.assertEqual(the_html, problem.get_html(), 'should be able to call get_html() twice')
# Check about masking
@@ -161,7 +161,7 @@ class CapaAnswerPoolTest(unittest.TestCase):
problem = new_loncapa_problem(xml_str)
the_html = problem.get_html()
self.assertRegex(the_html, r"<div>.*\[.*'wrong-1'.*'wrong-2'.*'correct-1'.*'wrong-3'.*'wrong-4'.*'correct-2'.*\].*</div>")
self.assertRegex(the_html, r"<div>.*\[.*'wrong-1'.*'wrong-2'.*'correct-1'.*'wrong-3'.*'wrong-4'.*'correct-2'.*\].*</div>") # lint-amnesty, pylint: disable=line-too-long
self.assertRegex(the_html, r"<div>\{.*'1_solution_1'.*'1_solution_2'.*\}</div>")
response = list(problem.responders.values())[0]
self.assertFalse(response.has_mask())

View File

@@ -212,7 +212,7 @@ class CAPAProblemTest(unittest.TestCase):
Verify that tag with question text is not removed when inputtype is not fully accessible.
"""
question = "Click the country which is home to the Pyramids."
xml = """
xml = """ # lint-amnesty, pylint: disable=duplicate-string-formatting-argument
<problem>
<p>{}</p>
<imageresponse>

View File

@@ -15,7 +15,7 @@ class CorrectMapTest(unittest.TestCase):
"""
def setUp(self):
super(CorrectMapTest, self).setUp()
super(CorrectMapTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.cmap = CorrectMap()
def test_set_input_properties(self):

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import unittest
import xml.sax.saxutils as saxutils
@@ -17,7 +17,7 @@ def extract_context(xml):
Given an xml element corresponding to the output of test_capa_system.render_template, get back the
original context
"""
return eval(xml.text)
return eval(xml.text) # lint-amnesty, pylint: disable=eval-used
def quote_attr(s):
@@ -64,7 +64,7 @@ class MathRenderTest(unittest.TestCase):
Make sure math renders properly.
'''
def check_parse(self, latex_in, mathjax_out):
def check_parse(self, latex_in, mathjax_out): # lint-amnesty, pylint: disable=missing-function-docstring
xml_str = """<math>{tex}</math>""".format(tex=latex_in)
element = etree.fromstring(xml_str)

View File

@@ -26,7 +26,7 @@ class CapaHtmlRenderTest(unittest.TestCase):
"""
def setUp(self):
super(CapaHtmlRenderTest, self).setUp()
super(CapaHtmlRenderTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.capa_system = test_capa_system()
def test_blank_problem(self):
@@ -308,7 +308,7 @@ class CapaHtmlRenderTest(unittest.TestCase):
the_html = problem.get_html()
self.assertRegex(the_html, r"<div>\s*</div>")
def _create_test_file(self, path, content_str):
def _create_test_file(self, path, content_str): # lint-amnesty, pylint: disable=missing-function-docstring
test_fp = self.capa_system.filestore.open(path, "w")
test_fp.write(content_str)
test_fp.close()

View File

@@ -21,7 +21,7 @@ class TemplateError(Exception):
"""
Error occurred while rendering a Mako template.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class TemplateTestCase(unittest.TestCase):
@@ -51,7 +51,7 @@ class TemplateTestCase(unittest.TestCase):
"""
Initialize the context.
"""
super(TemplateTestCase, self).setUp()
super(TemplateTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {}
def render_to_xml(self, context_dict):
@@ -64,7 +64,7 @@ class TemplateTestCase(unittest.TestCase):
try:
xml_str = capa_render_template(self.TEMPLATE_NAME, context_dict)
except:
raise TemplateError(exceptions.text_error_template().render())
raise TemplateError(exceptions.text_error_template().render()) # lint-amnesty, pylint: disable=raise-missing-from
# Attempt to construct an XML tree from the template
# This makes it easy to use XPath to make assertions, rather
@@ -74,7 +74,7 @@ class TemplateTestCase(unittest.TestCase):
try:
xml = etree.fromstring("<test>" + xml_str + "</test>")
except Exception as exc:
raise TemplateError("Could not parse XML from '{0}': {1}".format(
raise TemplateError("Could not parse XML from '{0}': {1}".format( # lint-amnesty, pylint: disable=raise-missing-from
xml_str, str(exc)))
else:
return xml
@@ -246,7 +246,7 @@ class ChoiceGroupTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'choicegroup.html'
def setUp(self):
super(ChoiceGroupTemplateTest, self).setUp()
super(ChoiceGroupTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
choices = [('1', 'choice 1'), ('2', 'choice 2'), ('3', 'choice 3')]
self.context = {
'id': '1',
@@ -493,7 +493,7 @@ class TextlineTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'textline.html'
def setUp(self):
super(TextlineTemplateTest, self).setUp()
super(TextlineTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': '1',
'status': Status('correct'),
@@ -618,7 +618,7 @@ class FormulaEquationInputTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'formulaequationinput.html'
def setUp(self):
super(FormulaEquationInputTemplateTest, self).setUp()
super(FormulaEquationInputTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': 2,
'value': 'PREFILLED_VALUE',
@@ -669,7 +669,7 @@ class AnnotationInputTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'annotationinput.html'
def setUp(self):
super(AnnotationInputTemplateTest, self).setUp()
super(AnnotationInputTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': 2,
'value': '<p>Test value</p>',
@@ -797,7 +797,7 @@ class MathStringTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'mathstring.html'
def setUp(self):
super(MathStringTemplateTest, self).setUp()
super(MathStringTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {'isinline': False, 'mathstr': '', 'tail': ''}
def test_math_string_inline(self):
@@ -839,7 +839,7 @@ class OptionInputTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'optioninput.html'
def setUp(self):
super(OptionInputTemplateTest, self).setUp()
super(OptionInputTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': 2,
'options': [],
@@ -900,7 +900,7 @@ class DragAndDropTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'drag_and_drop_input.html'
def setUp(self):
super(DragAndDropTemplateTest, self).setUp()
super(DragAndDropTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {'id': 2,
'drag_and_drop_json': '',
'value': 0,
@@ -957,7 +957,7 @@ class ChoiceTextGroupTemplateTest(TemplateTestCase):
'1_choiceinput_1_textinput_0': '0'}
def setUp(self):
super(ChoiceTextGroupTemplateTest, self).setUp()
super(ChoiceTextGroupTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
choices = [
(
'1_choiceinput_0bc',
@@ -1133,7 +1133,7 @@ class ChemicalEquationTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'chemicalequationinput.html'
def setUp(self):
super(ChemicalEquationTemplateTest, self).setUp()
super(ChemicalEquationTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': '1',
'status': Status('correct'),
@@ -1154,7 +1154,7 @@ class SchematicInputTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'schematicinput.html'
def setUp(self):
super(SchematicInputTemplateTest, self).setUp()
super(SchematicInputTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': '1',
'status': Status('correct'),
@@ -1186,7 +1186,7 @@ class CodeinputTemplateTest(TemplateTestCase):
TEMPLATE_NAME = 'codeinput.html'
def setUp(self):
super(CodeinputTemplateTest, self).setUp()
super(CodeinputTemplateTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.context = {
'id': '1',
'status': Status('correct'),

View File

@@ -93,7 +93,7 @@ class OptionInputTest(unittest.TestCase):
def test_option_parsing(self):
f = inputtypes.OptionInput.parse_options
def check(input, options):
def check(input, options): # lint-amnesty, pylint: disable=redefined-builtin
"""
Take list of options, confirm that output is in the silly doubled format
"""
@@ -119,7 +119,7 @@ class ChoiceGroupTest(unittest.TestCase):
Test choice groups, radio groups, and checkbox groups
"""
def check_group(self, tag, expected_input_type, expected_suffix):
def check_group(self, tag, expected_input_type, expected_suffix): # lint-amnesty, pylint: disable=missing-function-docstring
xml_str = """
<{tag}>
<choice correct="false" name="foil1"><text>This is foil One.</text></choice>
@@ -480,7 +480,7 @@ class MatlabTest(unittest.TestCase):
Test Matlab input types
"""
def setUp(self):
super(MatlabTest, self).setUp()
super(MatlabTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.rows = '10'
self.cols = '80'
self.tabsize = '4'
@@ -606,7 +606,7 @@ class MatlabTest(unittest.TestCase):
self.assertEqual(context, expected)
@patch('capa.inputtypes.time.time', return_value=10)
def test_rendering_while_queued(self, time):
def test_rendering_while_queued(self, time): # lint-amnesty, pylint: disable=unused-argument
state = {
'value': 'print "good evening"',
'status': 'incomplete',
@@ -660,7 +660,7 @@ class MatlabTest(unittest.TestCase):
self.assertNotIn('queuestate', self.the_input.input_state)
@patch('capa.inputtypes.time.time', return_value=10)
def test_ungraded_response_success(self, time):
def test_ungraded_response_success(self, time): # lint-amnesty, pylint: disable=unused-argument
queuekey = 'abcd'
input_state = {'queuekey': queuekey, 'queuestate': 'queued', 'queuetime': 5}
state = {'value': 'print "good evening"',
@@ -679,7 +679,7 @@ class MatlabTest(unittest.TestCase):
self.assertEqual(input_state['queue_msg'], inner_msg)
@patch('capa.inputtypes.time.time', return_value=10)
def test_ungraded_response_key_mismatch(self, time):
def test_ungraded_response_key_mismatch(self, time): # lint-amnesty, pylint: disable=unused-argument
queuekey = 'abcd'
input_state = {'queuekey': queuekey, 'queuestate': 'queued', 'queuetime': 5}
state = {'value': 'print "good evening"',
@@ -698,7 +698,7 @@ class MatlabTest(unittest.TestCase):
self.assertNotIn('queue_msg', input_state)
@patch('capa.inputtypes.time.time', return_value=20)
def test_matlab_response_timeout_not_exceeded(self, time):
def test_matlab_response_timeout_not_exceeded(self, time): # lint-amnesty, pylint: disable=unused-argument
state = {'input_state': {'queuestate': 'queued', 'queuetime': 5}}
elt = etree.fromstring(self.xml)
@@ -707,7 +707,7 @@ class MatlabTest(unittest.TestCase):
self.assertEqual(the_input.status, 'queued')
@patch('capa.inputtypes.time.time', return_value=45)
def test_matlab_response_timeout_exceeded(self, time):
def test_matlab_response_timeout_exceeded(self, time): # lint-amnesty, pylint: disable=unused-argument
state = {'input_state': {'queuestate': 'queued', 'queuetime': 5}}
elt = etree.fromstring(self.xml)
@@ -717,7 +717,7 @@ class MatlabTest(unittest.TestCase):
self.assertEqual(the_input.msg, 'No response from Xqueue within {} seconds. Aborted.'.format(XQUEUE_TIMEOUT))
@patch('capa.inputtypes.time.time', return_value=20)
def test_matlab_response_migration_of_queuetime(self, time):
def test_matlab_response_migration_of_queuetime(self, time): # lint-amnesty, pylint: disable=unused-argument
"""
Test if problem was saved before queuetime was introduced.
"""
@@ -737,7 +737,7 @@ class MatlabTest(unittest.TestCase):
the_input = lookup_tag('matlabinput')(system, elt, {})
data = {'submission': 'x = 1234;'}
response = the_input.handle_ajax("plot", data)
response = the_input.handle_ajax("plot", data) # lint-amnesty, pylint: disable=unused-variable
body = system.xqueue['interface'].send_to_queue.call_args[1]['body']
payload = json.loads(body)
@@ -856,12 +856,12 @@ class MatlabTest(unittest.TestCase):
the_input = self.input_class(test_capa_system(), elt, state)
context = the_input._get_render_context() # pylint: disable=protected-access
self.maxDiff = None
expected = fromstring(u'\n<div class="matlabResponse"><div class="commandWindowOutput" style="white-space: pre;"> <strong>if</strong> Conditionally execute statements.\nThe general form of the <strong>if</strong> statement is\n\n <strong>if</strong> 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 <strong>if</strong>\'s.\nThe expression is usually of the form expr rop expr where \nrop is ==, &lt;, &gt;, &lt;=, &gt;=, or ~=.\n<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjAAAAGkCAIAAACgj==">\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 <a>relop</a>, <a>else</a>, <a>elseif</a>, <a>end</a>, <a>for</a>, <a>while</a>, <a>switch</a>.\n\nReference page in Help browser\n <a>doc if</a>\n\n</div><ul></ul></div>\n')
expected = fromstring(u'\n<div class="matlabResponse"><div class="commandWindowOutput" style="white-space: pre;"> <strong>if</strong> Conditionally execute statements.\nThe general form of the <strong>if</strong> statement is\n\n <strong>if</strong> 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 <strong>if</strong>\'s.\nThe expression is usually of the form expr rop expr where \nrop is ==, &lt;, &gt;, &lt;=, &gt;=, or ~=.\n<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjAAAAGkCAIAAACgj==">\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 <a>relop</a>, <a>else</a>, <a>elseif</a>, <a>end</a>, <a>for</a>, <a>while</a>, <a>switch</a>.\n\nReference page in Help browser\n <a>doc if</a>\n\n</div><ul></ul></div>\n') # lint-amnesty, pylint: disable=line-too-long
received = fromstring(context['queue_msg'])
html_tree_equal(received, expected)
def test_rendering_with_invalid_queue_msg(self):
self.the_input.queue_msg = (u"<div class='matlabResponse'><div style='white-space:pre' class='commandWindowOutput'>"
self.the_input.queue_msg = (u"<div class='matlabResponse'><div style='white-space:pre' class='commandWindowOutput'>" # lint-amnesty, pylint: disable=line-too-long
u"\nans =\n\n\u0002\n\n</div><ul></ul></div>")
context = self.the_input._get_render_context() # pylint: disable=protected-access
@@ -1003,7 +1003,7 @@ class ImageInputTest(unittest.TestCase):
"""
Check that image inputs work
"""
def check(self, value, egx, egy):
def check(self, value, egx, egy): # lint-amnesty, pylint: disable=missing-function-docstring
height = '78'
width = '427'
src = 'http://www.edx.org/cowclicker.jpg'
@@ -1151,7 +1151,7 @@ class ChemicalEquationTest(unittest.TestCase):
Check that chemical equation inputs work.
"""
def setUp(self):
super(ChemicalEquationTest, self).setUp()
super(ChemicalEquationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.size = "42"
xml_str = """<chemicalequationinput id="prob_1_2" size="{size}"/>""".format(size=self.size)
@@ -1246,7 +1246,7 @@ class FormulaEquationTest(unittest.TestCase):
Check that formula equation inputs work.
"""
def setUp(self):
super(FormulaEquationTest, self).setUp()
super(FormulaEquationTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.size = "42"
xml_str = """<formulaequationinput id="prob_1_2" size="{size}"/>""".format(size=self.size)
@@ -1427,12 +1427,12 @@ class DragAndDropTest(unittest.TestCase):
"base_image": "/dummy-static/images/about_1.png",
"draggables": [
{"can_reuse": "", "label": "Label 1", "id": "1", "icon": "", "target_fields": []},
{"can_reuse": "", "label": "cc", "id": "name_with_icon", "icon": "/dummy-static/images/cc.jpg", "target_fields": []},
{"can_reuse": "", "label": "arrow-left", "id": "with_icon", "icon": "/dummy-static/images/arrow-left.png", "target_fields": []},
{"can_reuse": "", "label": "cc", "id": "name_with_icon", "icon": "/dummy-static/images/cc.jpg", "target_fields": []}, # lint-amnesty, pylint: disable=line-too-long
{"can_reuse": "", "label": "arrow-left", "id": "with_icon", "icon": "/dummy-static/images/arrow-left.png", "target_fields": []}, # lint-amnesty, pylint: disable=line-too-long
{"can_reuse": "", "label": "Label2", "id": "5", "icon": "", "target_fields": []},
{"can_reuse": "", "label": "Mute", "id": "2", "icon": "/dummy-static/images/mute.png", "target_fields": []},
{"can_reuse": "", "label": "spinner", "id": "name_label_icon3", "icon": "/dummy-static/images/spinner.gif", "target_fields": []},
{"can_reuse": "", "label": "Star", "id": "name4", "icon": "/dummy-static/images/volume.png", "target_fields": []},
{"can_reuse": "", "label": "Mute", "id": "2", "icon": "/dummy-static/images/mute.png", "target_fields": []}, # lint-amnesty, pylint: disable=line-too-long
{"can_reuse": "", "label": "spinner", "id": "name_label_icon3", "icon": "/dummy-static/images/spinner.gif", "target_fields": []}, # lint-amnesty, pylint: disable=line-too-long
{"can_reuse": "", "label": "Star", "id": "name4", "icon": "/dummy-static/images/volume.png", "target_fields": []}, # lint-amnesty, pylint: disable=line-too-long
{"can_reuse": "", "label": "Label3", "id": "7", "icon": "", "target_fields": []}],
"one_per_target": "True",
"targets": [

View File

@@ -53,9 +53,9 @@ class ResponseTest(unittest.TestCase):
maxDiff = None
def setUp(self):
super(ResponseTest, self).setUp()
super(ResponseTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
if self.xml_factory_class:
self.xml_factory = self.xml_factory_class()
self.xml_factory = self.xml_factory_class() # lint-amnesty, pylint: disable=not-callable
def build_problem(self, capa_system=None, **kwargs):
xml = self.xml_factory.build_xml(**kwargs)
@@ -944,7 +944,7 @@ class CodeResponseTest(ResponseTest): # pylint: disable=missing-class-docstring
xml_factory_class = CodeResponseXMLFactory
def setUp(self):
super(CodeResponseTest, self).setUp()
super(CodeResponseTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
grader_payload = json.dumps({"grader": "ps04/grade_square.py"})
self.problem = self.build_problem(initial_display="def square(x):",
@@ -1012,7 +1012,7 @@ class CodeResponseTest(ResponseTest): # pylint: disable=missing-class-docstring
self.assertEqual(self.problem.correct_map.get_dict(), old_cmap.get_dict()) # Deep comparison
for answer_id in answer_ids:
self.assertTrue(self.problem.correct_map.is_queued(answer_id)) # Should be still queued, since message undelivered
self.assertTrue(self.problem.correct_map.is_queued(answer_id)) # Should be still queued, since message undelivered # lint-amnesty, pylint: disable=line-too-long
# Correct queuekey, state should be updated
for correctness in ['correct', 'incorrect']:
@@ -1023,16 +1023,16 @@ class CodeResponseTest(ResponseTest): # pylint: disable=missing-class-docstring
new_cmap = CorrectMap()
new_cmap.update(old_cmap)
npoints = 1 if correctness == 'correct' else 0
new_cmap.set(answer_id=answer_id, npoints=npoints, correctness=correctness, msg=grader_msg, queuestate=None)
new_cmap.set(answer_id=answer_id, npoints=npoints, correctness=correctness, msg=grader_msg, queuestate=None) # lint-amnesty, pylint: disable=line-too-long
self.problem.update_score(xserver_msgs[correctness], queuekey=1000 + i)
self.assertEqual(self.problem.correct_map.get_dict(), new_cmap.get_dict())
for j, test_id in enumerate(answer_ids):
if j == i:
self.assertFalse(self.problem.correct_map.is_queued(test_id)) # Should be dequeued, message delivered
self.assertFalse(self.problem.correct_map.is_queued(test_id)) # Should be dequeued, message delivered # lint-amnesty, pylint: disable=line-too-long
else:
self.assertTrue(self.problem.correct_map.is_queued(test_id)) # Should be queued, message undelivered
self.assertTrue(self.problem.correct_map.is_queued(test_id)) # Should be queued, message undelivered # lint-amnesty, pylint: disable=line-too-long
def test_recentmost_queuetime(self):
'''
@@ -1586,7 +1586,7 @@ class NumericalResponseTest(ResponseTest): # pylint: disable=missing-class-docs
)
@mock.patch('capa.responsetypes.log')
def test_responsetype_i18n(self, mock_log):
def test_responsetype_i18n(self, mock_log): # lint-amnesty, pylint: disable=unused-argument
"""Test that LoncapaSystem has an i18n that works."""
staff_ans = "clearly bad syntax )[+1e"
problem = self.build_problem(answer=staff_ans, tolerance=1e-3)
@@ -1652,7 +1652,7 @@ class NumericalResponseTest(ResponseTest): # pylint: disable=missing-class-docs
def evaluator_side_effect(_, __, math_string):
"""Raise an error only for the student input."""
if math_string != '4':
raise err
raise err # lint-amnesty, pylint: disable=cell-var-from-loop
mock_eval.side_effect = evaluator_side_effect
with self.assertRaisesRegex(StudentInputError, msg_regex):
@@ -2320,7 +2320,7 @@ class CustomResponseTest(ResponseTest): # pylint: disable=missing-class-docstri
num = my_helper.seventeen()
""")
capa_system = test_capa_system()
capa_system.get_python_lib_zip = lambda: zipstring.getvalue()
capa_system.get_python_lib_zip = lambda: zipstring.getvalue() # lint-amnesty, pylint: disable=unnecessary-lambda
problem = self.build_problem(script=script, capa_system=capa_system)
self.assertEqual(problem.context['num'], 17)
@@ -2424,7 +2424,7 @@ class SchematicResponseTest(ResponseTest):
def test_check_function_randomization(self):
# The check function should get a random seed from the problem.
script = "correct = ['correct' if (submission[0]['num'] == {code}) else 'incorrect']".format(code=self._get_random_number_code())
script = "correct = ['correct' if (submission[0]['num'] == {code}) else 'incorrect']".format(code=self._get_random_number_code()) # lint-amnesty, pylint: disable=line-too-long
problem = self.build_problem(answer=script)
submission_dict = {'num': self._get_random_number_result(problem.seed)}
@@ -2445,7 +2445,7 @@ class SchematicResponseTest(ResponseTest):
problem.grade_answers(input_dict)
class AnnotationResponseTest(ResponseTest):
class AnnotationResponseTest(ResponseTest): # lint-amnesty, pylint: disable=missing-class-docstring
xml_factory_class = AnnotationResponseXMLFactory
def test_grade(self):

View File

@@ -12,7 +12,7 @@ class CapaShuffleTest(unittest.TestCase):
"""Capa problem tests for shuffling and choice-name masking."""
def setUp(self):
super(CapaShuffleTest, self).setUp()
super(CapaShuffleTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.system = test_capa_system()
def test_shuffle_4_choices(self):
@@ -113,7 +113,7 @@ class CapaShuffleTest(unittest.TestCase):
problem = new_loncapa_problem(xml_str, seed=0) # yields: C E A B D F
# Donut -> Zonut to show that there is not some hidden alphabetic ordering going on
the_html = problem.get_html()
self.assertRegex(the_html, r"<div>.*\[.*'Chocolate'.*'Eggplant'.*'Apple'.*'Banana'.*'Zonut'.*'Filet Mignon'.*\].*</div>")
self.assertRegex(the_html, r"<div>.*\[.*'Chocolate'.*'Eggplant'.*'Apple'.*'Banana'.*'Zonut'.*'Filet Mignon'.*\].*</div>") # lint-amnesty, pylint: disable=line-too-long
def test_shuffle_false(self):
xml_str = textwrap.dedent("""

View File

@@ -18,7 +18,7 @@ class CapaTargetedFeedbackTest(unittest.TestCase):
'''
def setUp(self):
super(CapaTargetedFeedbackTest, self).setUp()
super(CapaTargetedFeedbackTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.system = test_capa_system()
def test_no_targeted_feedback(self):

View File

@@ -24,10 +24,10 @@ class UtilTest(unittest.TestCase):
"""Tests for util"""
def setUp(self):
super(UtilTest, self).setUp()
super(UtilTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.system = test_capa_system()
def test_compare_with_tolerance(self):
def test_compare_with_tolerance(self): # lint-amnesty, pylint: disable=too-many-statements
# Test default tolerance '0.001%' (it is relative)
result = compare_with_tolerance(100.0, 100.0)
self.assertTrue(result)

View File

@@ -1,4 +1,4 @@
#
# # lint-amnesty, pylint: disable=missing-module-docstring
# LMS Interface to external queueing system (xqueue)
#
@@ -93,7 +93,7 @@ class XQueueInterface(object):
# log the send to xqueue
header_info = json.loads(header)
queue_name = header_info.get('queue_name', u'')
queue_name = header_info.get('queue_name', u'') # lint-amnesty, pylint: disable=unused-variable
# Attempt to send to queue
(error, msg) = self._send_to_queue(header, body, files_to_upload)
@@ -113,14 +113,14 @@ class XQueueInterface(object):
return error, msg
def _login(self):
def _login(self): # lint-amnesty, pylint: disable=missing-function-docstring
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):
def _send_to_queue(self, header, body, files_to_upload): # lint-amnesty, pylint: disable=missing-function-docstring
payload = {
'xqueue_header': header,
'xqueue_body': body
@@ -132,7 +132,7 @@ class XQueueInterface(object):
return self._http_post(self.url + '/xqueue/submit/', payload, files=files)
def _http_post(self, url, data, files=None):
def _http_post(self, url, data, files=None): # lint-amnesty, pylint: disable=missing-function-docstring
try:
response = self.session.post(
url, data=data, files=files, timeout=(CONNECT_TIMEOUT, READ_TIMEOUT)

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=django-not-configured, missing-module-docstring
from setuptools import find_packages, setup

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Defuse vulnerabilities in XML packages.
"""

View File

@@ -13,7 +13,7 @@ For processing xml always prefer this over using lxml.etree directly.
from lxml.etree import XMLParser as _XMLParser
from lxml.etree import *
from lxml.etree import * # lint-amnesty, pylint: disable=redefined-builtin
from lxml.etree import _Element, _ElementTree
# This should be imported after lxml.etree so that it overrides the following attributes.
@@ -28,4 +28,4 @@ class XMLParser(_XMLParser): # pylint: disable=function-redefined
def __init__(self, *args, **kwargs):
if "resolve_entities" not in kwargs:
kwargs["resolve_entities"] = False
super(XMLParser, self).__init__(*args, **kwargs)
super(XMLParser, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Setup.py for safe_lxml.
"""

View File

@@ -1,4 +1,4 @@
"""
""" # lint-amnesty, pylint: disable=django-not-configured
Standard resistor values.
Commonly used for verifying electronic components in circuit classes are

View File

@@ -1,3 +1,3 @@
#!/usr/bin/python
#!/usr/bin/python # lint-amnesty, pylint: disable=django-not-configured, missing-module-docstring
from .loncapa_check import *
from .loncapa_check import * # lint-amnesty, pylint: disable=redefined-builtin

View File

@@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/python # lint-amnesty, pylint: disable=missing-module-docstring
#
# File: mitx/lib/loncapa/loncapa_check.py
#
@@ -26,9 +26,9 @@ def lc_choose(index, *args):
'''
try:
return args[int(index) - 1]
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except, unused-variable
pass
if len(args):
if len(args): # lint-amnesty, pylint: disable=len-as-condition
return args[0]
raise Exception(
"loncapa_check.lc_choose error, index={index}, args={args}".format(

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from setuptools import setup

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import json
import unittest
@@ -42,7 +42,7 @@ class Test_PositionsCompare(unittest.TestCase):
self.assertEqual(PositionsCompare([3.5, 4.5]), PositionsCompare([5, 7]))
class Test_DragAndDrop_Grade(unittest.TestCase):
class Test_DragAndDrop_Grade(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_targets_are_draggable_1(self):
user_input = json.dumps([
@@ -775,7 +775,7 @@ class Test_DragAndDrop_Grade(unittest.TestCase):
self.assertTrue(draganddrop.grade(user_input, correct_answer))
class Test_DragAndDrop_Populate(unittest.TestCase):
class Test_DragAndDrop_Populate(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_1(self):
correct_answer = {'1': [[40, 10], 29], 'name_with_icon': [20, 20]}
@@ -793,7 +793,7 @@ class Test_DragAndDrop_Populate(unittest.TestCase):
self.assertEqual(user_positions, dnd.user_positions)
class Test_DraAndDrop_Compare_Positions(unittest.TestCase):
class Test_DraAndDrop_Compare_Positions(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_1(self):
dnd = draganddrop.DragAndDrop({'1': 't1'}, '[{"1": "t1"}]')
@@ -844,7 +844,7 @@ class Test_DraAndDrop_Compare_Positions(unittest.TestCase):
flag='anyof'))
def suite():
def suite(): # lint-amnesty, pylint: disable=missing-function-docstring
testcases = [Test_PositionsCompare,
Test_DragAndDrop_Populate,

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=django-not-configured, missing-module-docstring
from setuptools import setup
setup(

View File

@@ -1,2 +1,3 @@
from .formula import *
# lint-amnesty, pylint: disable=missing-module-docstring
from .formula import * # lint-amnesty, pylint: disable=django-not-configured
from .symmath_check import *

View File

@@ -21,7 +21,7 @@ import unicodedata
#import subprocess
from copy import deepcopy
from functools import reduce
from xml.sax.saxutils import unescape
from xml.sax.saxutils import unescape # lint-amnesty, pylint: disable=unused-import
import six
import sympy
@@ -210,7 +210,7 @@ class formula(object):
for k in xml:
tag = gettag(k)
if tag == 'mi' or tag == 'ci':
if tag == 'mi' or tag == 'ci': # lint-amnesty, pylint: disable=consider-using-in
usym = six.text_type(k.text)
try:
udata = unicodedata.name(usym)
@@ -227,7 +227,7 @@ class formula(object):
self.fix_greek_in_mathml(k)
return xml
def preprocess_pmathml(self, xml):
def preprocess_pmathml(self, xml): # lint-amnesty, pylint: disable=too-many-statements
r"""
Pre-process presentation MathML from ASCIIMathML to make it more
acceptable for SnuggleTeX, and also to accomodate some sympy
@@ -420,7 +420,7 @@ class formula(object):
self.xml = xml # pylint: disable=attribute-defined-outside-init
return self.xml
def get_content_mathml(self):
def get_content_mathml(self): # lint-amnesty, pylint: disable=missing-function-docstring
if self.the_cmathml:
return self.the_cmathml
@@ -436,7 +436,7 @@ class formula(object):
cmathml = property(get_content_mathml, None, None, 'content MathML representation')
def make_sympy(self, xml=None):
def make_sympy(self, xml=None): # lint-amnesty, pylint: disable=too-many-statements
"""
Return sympy expression for the math formula.
The math formula is converted to Content MathML then that is parsed.
@@ -457,11 +457,11 @@ class formula(object):
cmml = self.cmathml
xml = etree.fromstring(str(cmml))
except Exception as err:
if 'conversion from Presentation MathML to Content MathML was not successful' in cmml:
if 'conversion from Presentation MathML to Content MathML was not successful' in cmml: # lint-amnesty, pylint: disable=unsupported-membership-test
msg = "Illegal math expression"
else:
msg = 'Err %s while converting cmathml to xml; cmml=%s' % (err, cmml)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
xml = self.fix_greek_in_mathml(xml)
self.the_sympy = self.make_sympy(xml[0])
else:
@@ -482,14 +482,14 @@ class formula(object):
def op_minus(*args):
if len(args) == 1:
return -args[0]
if not len(args) == 2:
if not len(args) == 2: # lint-amnesty, pylint: disable=unneeded-not
raise Exception('minus given wrong number of arguments!')
#return sympy.Add(args[0],-args[1])
return args[0] - args[1]
opdict = {
'plus': op_plus,
'divide': operator.div,
'divide': operator.div, # lint-amnesty, pylint: disable=no-member
'times': op_times,
'minus': op_minus,
'root': sympy.sqrt,
@@ -546,7 +546,7 @@ class formula(object):
except Exception as err:
self.args = args # pylint: disable=attribute-defined-outside-init
self.op = op # pylint: disable=attribute-defined-outside-init, invalid-name
raise Exception('[formula] error=%s failed to apply %s to args=%s' % (err, opstr, args))
raise Exception('[formula] error=%s failed to apply %s to args=%s' % (err, opstr, args)) # lint-amnesty, pylint: disable=raise-missing-from
return res
else:
raise Exception('[formula]: unknown operator tag %s' % (opstr))

View File

@@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/python # lint-amnesty, pylint: disable=missing-module-docstring
# -*- coding: utf-8 -*-
#
# File: symmath_check.py
@@ -16,7 +16,7 @@ from markupsafe import escape
from openedx.core.djangolib.markup import HTML
from .formula import *
from .formula import * # lint-amnesty, pylint: disable=wildcard-import
log = logging.getLogger(__name__)
@@ -26,7 +26,7 @@ log = logging.getLogger(__name__)
# This is one of the main entry points to call.
def symmath_check_simple(expect, ans, adict={}, symtab=None, extra_options=None):
def symmath_check_simple(expect, ans, adict={}, symtab=None, extra_options=None): # lint-amnesty, pylint: disable=dangerous-default-value, unused-argument
"""
Check a symbolic mathematical expression using sympy.
The input is an ascii string (not MathML) converted to math using sympy.sympify.
@@ -51,7 +51,7 @@ def symmath_check_simple(expect, ans, adict={}, symtab=None, extra_options=None)
abcsym=options['__ABC__'],
symtab=symtab,
)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
return {'ok': False,
'msg': HTML('Error {err}<br/>Failed in evaluating check({expect},{ans})').format(
err=err, expect=expect, ans=ans
@@ -62,7 +62,7 @@ def symmath_check_simple(expect, ans, adict={}, symtab=None, extra_options=None)
# pretty generic checking function
def check(expect, given, numerical=False, matrix=False, normphase=False, abcsym=False, do_qubit=True, symtab=None, dosimplify=False):
def check(expect, given, numerical=False, matrix=False, normphase=False, abcsym=False, do_qubit=True, symtab=None, dosimplify=False): # lint-amnesty, pylint: disable=line-too-long
"""
Returns dict with
@@ -93,19 +93,19 @@ def check(expect, given, numerical=False, matrix=False, normphase=False, abcsym=
threshold = float(st)
numerical = True
if str(given) == '' and not str(expect) == '':
if str(given) == '' and not str(expect) == '': # lint-amnesty, pylint: disable=unneeded-not
return {'ok': False, 'msg': ''}
try:
xgiven = my_sympify(given, normphase, matrix, do_qubit=do_qubit, abcsym=abcsym, symtab=symtab)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
return {'ok': False, 'msg': HTML('Error {err}<br/> in evaluating your expression "{given}"').format(
err=err, given=given
)}
try:
xexpect = my_sympify(expect, normphase, matrix, do_qubit=do_qubit, abcsym=abcsym, symtab=symtab)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
return {'ok': False, 'msg': HTML('Error {err}<br/> in evaluating OUR expression "{expect}"').format(
err=err, expect=expect
)}
@@ -113,12 +113,12 @@ def check(expect, given, numerical=False, matrix=False, normphase=False, abcsym=
if 'autonorm' in flags: # normalize trace of matrices
try:
xgiven /= xgiven.trace()
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
return {'ok': False, 'msg': HTML('Error {err}<br/> in normalizing trace of your expression {xgiven}').
format(err=err, xgiven=to_latex(xgiven))}
try:
xexpect /= xexpect.trace()
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
return {'ok': False, 'msg': HTML('Error {err}<br/> in normalizing trace of OUR expression {xexpect}').
format(err=err, xexpect=to_latex(xexpect))}
@@ -172,7 +172,7 @@ def is_within_tolerance(expected, actual, tolerance):
# This is one of the main entry points to call.
def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None):
def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None): # lint-amnesty, pylint: disable=too-many-statements
"""
Check a symbolic mathematical expression using sympy.
The input may be presentation MathML. Uses formula.
@@ -220,7 +220,7 @@ def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None
# parse expected answer
try:
fexpect = my_sympify(str(expect), matrix=do_matrix, do_qubit=do_qubit)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
msg += HTML('<p>Error {err} in parsing OUR expected answer "{expect}"</p>').format(err=err, expect=expect)
return {'ok': False, 'msg': make_error_message(msg)}
@@ -228,7 +228,7 @@ def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None
# if expected answer is a number, try parsing provided answer as a number also
try:
fans = my_sympify(str(ans), matrix=do_matrix, do_qubit=do_qubit)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
fans = None
# do a numerical comparison if both expected and answer are numbers
@@ -256,7 +256,7 @@ def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None
# convert mathml answer to formula
try:
mmlans = dynamath[0] if dynamath else None
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
mmlans = None
if not mmlans:
return {'ok': False, 'msg': '[symmath_check] failed to get MathML for input; dynamath=%s' % dynamath}
@@ -268,7 +268,7 @@ def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None
try:
fsym = f.sympy
msg += HTML('<p>You entered: {sympy}</p>').format(sympy=to_latex(f.sympy))
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
log.exception("Error evaluating expression '%s' as a valid equation", ans)
msg += HTML("<p>Error in evaluating your expression '{ans}' as a valid equation</p>").format(ans=ans)
if "Illegal math" in str(err):
@@ -309,7 +309,7 @@ def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None
except sympy.ShapeError:
msg += HTML("<p>Error - your input vector or matrix has the wrong dimensions")
return {'ok': False, 'msg': make_error_message(msg)}
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
msg += HTML("<p>Error %s in comparing expected (a list) and your answer</p>").format(escape(str(err)))
if DEBUG:
msg += HTML("<p/><pre>{format_exc}</pre>").format(format_exc=traceback.format_exc())
@@ -320,7 +320,7 @@ def symmath_check(expect, ans, dynamath=None, options=None, debug=None, xml=None
#fexpect = fexpect.simplify()
try:
diff = (fexpect - fsym)
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
diff = None
if DEBUG:

View File

@@ -16,13 +16,13 @@ def stripXML(xml):
return xml
class FormulaTest(unittest.TestCase):
class FormulaTest(unittest.TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
# for readability later
mathml_start = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mstyle displaystyle="true">'
mathml_end = '</mstyle></math>'
def setUp(self):
super(FormulaTest, self).setUp()
super(FormulaTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.formulaInstance = formula('')
def test_replace_mathvariants(self):

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from unittest import TestCase
from six.moves import range
@@ -6,9 +6,9 @@ from six.moves import range
from .symmath_check import symmath_check
class SymmathCheckTest(TestCase):
class SymmathCheckTest(TestCase): # lint-amnesty, pylint: disable=missing-class-docstring
def test_symmath_check_integers(self):
number_list = [i for i in range(-100, 100)]
number_list = [i for i in range(-100, 100)] # lint-amnesty, pylint: disable=unnecessary-comprehension
self._symmath_check_numbers(number_list)
def test_symmath_check_floats(self):
@@ -73,7 +73,7 @@ class SymmathCheckTest(TestCase):
self.assertTrue('ok' in result and not result['ok'])
self.assertNotIn('fail', result['msg'])
def _symmath_check_numbers(self, number_list):
def _symmath_check_numbers(self, number_list): # lint-amnesty, pylint: disable=missing-function-docstring
for n in number_list:

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=django-not-configured, missing-module-docstring
from setuptools import find_packages, setup

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import logging
import textwrap
@@ -107,7 +107,7 @@ class AnnotatableBlock(
HIGHLIGHT_COLORS = ['yellow', 'orange', 'purple', 'blue', 'green']
def _get_annotation_class_attr(self, index, el):
def _get_annotation_class_attr(self, index, el): # lint-amnesty, pylint: disable=unused-argument
""" Returns a dict with the CSS class attribute to set on the annotation
and an XML key to delete from the element.
"""
@@ -125,7 +125,7 @@ class AnnotatableBlock(
return {'class': attr}
def _get_annotation_data_attr(self, index, el):
def _get_annotation_data_attr(self, index, el): # lint-amnesty, pylint: disable=unused-argument
""" Returns a dict in which the keys are the HTML data attributes
to set on the annotation element. Each data attribute has a
corresponding 'value' and (optional) '_delete' key to specify
@@ -139,7 +139,7 @@ class AnnotatableBlock(
'problem': 'data-problem-id'
}
for xml_key in attrs_map.keys():
for xml_key in attrs_map.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
if xml_key in el.attrib:
value = el.get(xml_key, '')
html_key = attrs_map[xml_key]
@@ -155,7 +155,7 @@ class AnnotatableBlock(
el.tag = 'span'
for key in attr.keys():
for key in attr.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
el.set(key, attr[key]['value'])
if '_delete' in attr[key] and attr[key]['_delete'] is not None:
delete_key = attr[key]['_delete']
@@ -203,7 +203,7 @@ class AnnotatableBlock(
return self.system.render_template('annotatable.html', context)
def student_view(self, context):
def student_view(self, context): # lint-amnesty, pylint: disable=unused-argument
"""
Renders the output that a student will see.
"""

View File

@@ -31,7 +31,7 @@ def get_extension(srcurl):
return 'video/' + file_ext.replace('.', '')
class MLStripper(HTMLParser):
class MLStripper(HTMLParser): # lint-amnesty, pylint: disable=abstract-method
"helper function for html_to_text below"
def __init__(self):
HTMLParser.__init__(self)

View File

@@ -18,7 +18,7 @@ new_contract('CourseKey', CourseKey)
new_contract('datetime', datetime)
new_contract('basestring', six.string_types[0])
if six.PY2:
new_contract('long', long)
new_contract('long', long) # lint-amnesty, pylint: disable=undefined-variable
else:
new_contract('long', int)
new_contract('AssetElement', lambda x: isinstance(x, etree._Element) and x.tag == "asset") # pylint: disable=protected-access
@@ -199,7 +199,7 @@ class AssetMetadata(object):
continue
elif tag == 'locked':
# Boolean.
value = True if value == "true" else False
value = True if value == "true" else False # lint-amnesty, pylint: disable=simplifiable-if-expression
elif value == 'None':
# None.
value = None

View File

@@ -26,21 +26,21 @@ class AssetException(Exception):
"""
Base exception class for all exceptions related to assets.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class AssetMetadataNotFound(AssetException):
"""
Thrown when no asset metadata is present in the course modulestore for the particular asset requested.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class AssetMetadataFoundTemporary(AssetException):
"""
TEMPORARY: Thrown if asset metadata is actually found in the course modulestore.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class AssetManager(object):

View File

@@ -21,7 +21,7 @@ class TestAssetXml(unittest.TestCase):
"""
def setUp(self):
super(TestAssetXml, self).setUp()
super(TestAssetXml, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
xsd_filename = "assets.xsd"

View File

@@ -41,7 +41,7 @@ def process_includes(fn):
# insert new XML into tree in place of include
parent.insert(parent.index(next_include), incxml)
except Exception:
except Exception: # lint-amnesty, pylint: disable=broad-except
# Log error
msg = "Error in problem xml include: %s" % (
etree.tostring(next_include, pretty_print=True))
@@ -65,7 +65,7 @@ def process_includes(fn):
return from_xml
class SemanticSectionDescriptor(XModuleDescriptor):
class SemanticSectionDescriptor(XModuleDescriptor): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring
resources_dir = None
@classmethod
@@ -89,7 +89,7 @@ class SemanticSectionDescriptor(XModuleDescriptor):
return system.process_xml(etree.tostring(xml_object))
class TranslateCustomTagDescriptor(XModuleDescriptor):
class TranslateCustomTagDescriptor(XModuleDescriptor): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring
resources_dir = None
@classmethod

View File

@@ -112,7 +112,7 @@ class ComplexEncoder(json.JSONEncoder):
"""
Extend the JSON encoder to correctly handle complex numbers
"""
def default(self, obj): # pylint: disable=method-hidden
def default(self, obj): # lint-amnesty, pylint: disable=arguments-differ, method-hidden
"""
Print a nicely formatted complex number, or default to the JSON encoder
"""
@@ -294,7 +294,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
return self.seed
@cached_property
def lcp(self):
def lcp(self): # lint-amnesty, pylint: disable=method-hidden, missing-function-docstring
try:
lcp = self.new_lcp(self.get_state_for_lcp())
except Exception as err: # pylint: disable=broad-except
@@ -446,7 +446,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
'graded': self.graded,
})
def handle_fatal_lcp_error(self, error):
def handle_fatal_lcp_error(self, error): # lint-amnesty, pylint: disable=missing-function-docstring
log.exception(u"LcpFatalError Encountered for {block}".format(block=str(self.location)))
if error:
return(
@@ -876,7 +876,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
'correcthint', 'regexphint', 'additional_answer', 'stringequalhint', 'compoundhint',
'stringequalhint']
for tag in tags:
html = re.sub(r'<%s.*?>.*?</%s>' % (tag, tag), '', html, flags=re.DOTALL) # xss-lint: disable=python-interpolate-html
html = re.sub(r'<%s.*?>.*?</%s>' % (tag, tag), '', html, flags=re.DOTALL) # xss-lint: disable=python-interpolate-html # lint-amnesty, pylint: disable=line-too-long
# Some of these tags span multiple lines
# Note: could probably speed this up by calling sub() once with a big regex
# vs. simply calling sub() many times as we have here.
@@ -1066,7 +1066,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
event_info = dict()
event_info['problem_id'] = text_type(self.location)
self.track_function_unmask('showanswer', event_info)
if not self.answer_available():
if not self.answer_available(): # lint-amnesty, pylint: disable=no-else-raise
raise NotFoundError('Answer is not available')
else:
answers = self.lcp.get_question_answers()
@@ -1155,7 +1155,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
# If key has no underscores, then partition
# will return (key, '', '')
# We detect this and raise an error
if not name:
if not name: # lint-amnesty, pylint: disable=no-else-raise
raise ValueError(u"{key} must contain at least one underscore".format(key=key))
else:
@@ -1176,7 +1176,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
val = json.loads(data[key])
# If the submission wasn't deserializable, raise an error.
except(KeyError, ValueError):
raise ValueError(
raise ValueError( # lint-amnesty, pylint: disable=raise-missing-from
u"Invalid submission: {val} for {key}".format(val=data[key], key=key)
)
else:
@@ -1184,7 +1184,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
# If the name already exists, then we don't want
# to override it. Raise an error instead
if name in answers:
if name in answers: # lint-amnesty, pylint: disable=no-else-raise
raise ValueError(u"Key {name} already exists in answers dict".format(name=name))
else:
answers[name] = val
@@ -1227,7 +1227,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
answers_without_files = convert_files_to_filenames(answers)
event_info['answers'] = answers_without_files
metric_name = u'capa.check_problem.{}'.format
metric_name = u'capa.check_problem.{}'.format # lint-amnesty, pylint: disable=unused-variable
# Can override current time
current_time = datetime.datetime.now(utc)
if override_time is not False:
@@ -1682,7 +1682,7 @@ class CapaMixin(ScorableXBlockMixin, CapaFields):
try:
self.update_correctness()
calculated_score = self.calculate_score()
except (StudentInputError, ResponseError, LoncapaProblemError) as inst:
except (StudentInputError, ResponseError, LoncapaProblemError) as inst: # lint-amnesty, pylint: disable=unused-variable
log.warning("Input error in capa_module:problem_rescore", exc_info=True)
event_info['failure'] = 'input_error'
self.track_function_unmask('problem_rescore_fail', event_info)

View File

@@ -30,7 +30,7 @@ from xmodule.x_module import (
)
from xmodule.xml_module import XmlMixin
from .capa_base import CapaMixin, ComplexEncoder, _
from .capa_base import CapaMixin, ComplexEncoder, _ # lint-amnesty, pylint: disable=unused-import
log = logging.getLogger("edx.courseware")
@@ -95,8 +95,8 @@ class ProblemBlock(
]
}
def bind_for_student(self, *args, **kwargs):
super(ProblemBlock, self).bind_for_student(*args, **kwargs)
def bind_for_student(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs
super(ProblemBlock, self).bind_for_student(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
# Capa was an XModule. When bind_for_student() was called on it with a new runtime, a new CapaModule object
# was initialized when XModuleDescriptor._xmodule() was called next. self.lcp was constructed in CapaModule
@@ -111,7 +111,7 @@ class ProblemBlock(
# self.score is initialized in self.lcp but in this method is accessed before self.lcp so just call it first.
try:
self.lcp
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
html = self.handle_fatal_lcp_error(err if show_detailed_errors else None)
else:
html = self.get_html()
@@ -132,7 +132,7 @@ class ProblemBlock(
return self.student_view(context)
else:
# Show a message that this content requires users to login/enroll.
return super(ProblemBlock, self).public_view(context)
return super(ProblemBlock, self).public_view(context) # lint-amnesty, pylint: disable=super-with-arguments
def author_view(self, context):
"""
@@ -163,7 +163,7 @@ class ProblemBlock(
<other request-specific values here > }
"""
# self.score is initialized in self.lcp but in this method is accessed before self.lcp so just call it first.
self.lcp
self.lcp # lint-amnesty, pylint: disable=pointless-statement
handlers = {
'hint_button': self.hint_button,
'problem_get': self.get_problem,
@@ -207,7 +207,7 @@ class ProblemBlock(
_, _, traceback_obj = sys.exc_info()
six.reraise(ProcessingError, ProcessingError(not_found_error_message), traceback_obj)
except Exception:
except Exception: # lint-amnesty, pylint: disable=broad-except
log.exception(
"Unknown error when dispatching %s to %s for user %s",
dispatch,
@@ -275,7 +275,7 @@ class ProblemBlock(
@property
def non_editable_metadata_fields(self):
non_editable_fields = super(ProblemBlock, self).non_editable_metadata_fields
non_editable_fields = super(ProblemBlock, self).non_editable_metadata_fields # lint-amnesty, pylint: disable=super-with-arguments
non_editable_fields.extend([
ProblemBlock.due,
ProblemBlock.graceperiod,
@@ -301,7 +301,7 @@ class ProblemBlock(
"""
Return dictionary prepared with module content and type for indexing.
"""
xblock_body = super(ProblemBlock, self).index_dictionary()
xblock_body = super(ProblemBlock, self).index_dictionary() # lint-amnesty, pylint: disable=super-with-arguments
# Make optioninput's options index friendly by replacing the actual tag with the values
capa_content = re.sub(r'<optioninput options="\(([^"]+)\)".*?>\s*|\S*<\/optioninput>', r'\1', self.data)

View File

@@ -194,7 +194,7 @@ class ConditionalBlock(
"""
Create an instance of the Conditional XBlock.
"""
super(ConditionalBlock, self).__init__(*args, **kwargs)
super(ConditionalBlock, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
# Convert sources xml_attribute to a ReferenceList field type so Location/Locator
# substitution can be done.
if not self.sources_list:
@@ -208,7 +208,7 @@ class ConditionalBlock(
for item in ConditionalBlock.parse_sources(self.xml_attributes)
]
def is_condition_satisfied(self):
def is_condition_satisfied(self): # lint-amnesty, pylint: disable=missing-function-docstring
attr_name = self.conditions_map[self.conditional_attr]
if self.conditional_value and self.get_required_blocks:
@@ -360,7 +360,7 @@ class ConditionalBlock(
try:
descriptor = system.process_xml(etree.tostring(child, encoding='unicode'))
children.append(descriptor.scope_ids.usage_id)
except:
except: # lint-amnesty, pylint: disable=bare-except
msg = "Unable to load child when parsing Conditional."
log.exception(msg)
system.error_tracker(msg)
@@ -390,7 +390,7 @@ class ConditionalBlock(
return xml_object
def validate(self):
validation = super(ConditionalBlock, self).validate()
validation = super(ConditionalBlock, self).validate() # lint-amnesty, pylint: disable=super-with-arguments
if not self.sources_list:
conditional_validation = StudioValidation(self.location)
conditional_validation.add(
@@ -407,7 +407,7 @@ class ConditionalBlock(
@property
def non_editable_metadata_fields(self):
non_editable_fields = super(ConditionalBlock, self).non_editable_metadata_fields
non_editable_fields = super(ConditionalBlock, self).non_editable_metadata_fields # lint-amnesty, pylint: disable=super-with-arguments
non_editable_fields.extend([
ConditionalBlock.due,
ConditionalBlock.show_tag_list,

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import logging
import os
@@ -26,11 +26,11 @@ VERSIONED_ASSETS_PREFIX = '/assets/courseware'
VERSIONED_ASSETS_PATTERN = r'/assets/courseware/(v[\d]/)?([a-f0-9]{32})'
class StaticContent(object):
class StaticContent(object): # lint-amnesty, pylint: disable=missing-class-docstring
def __init__(self, loc, name, content_type, data, last_modified_at=None, thumbnail_location=None, import_path=None,
length=None, locked=False, content_digest=None):
self.location = loc
self.name = name # a display string which can be edited, and thus not part of the location which needs to be fixed
self.name = name # a display string which can be edited, and thus not part of the location which needs to be fixed # lint-amnesty, pylint: disable=line-too-long
self.content_type = content_type
self._data = data
self.length = length
@@ -70,7 +70,7 @@ class StaticContent(object):
)
@staticmethod
def compute_location(course_key, path, revision=None, is_thumbnail=False):
def compute_location(course_key, path, revision=None, is_thumbnail=False): # lint-amnesty, pylint: disable=unused-argument
"""
Constructs a location object for static content.
@@ -111,10 +111,10 @@ class StaticContent(object):
@staticmethod
def get_static_path_from_location(location):
"""
This utility static method will take a location identifier and create a 'durable' /static/.. URL representation of it.
This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of
This utility static method will take a location identifier and create a 'durable' /static/.. URL representation of it. # lint-amnesty, pylint: disable=line-too-long
This link is 'durable' as it can maintain integrity across cloning of courseware across course-ids, e.g. reruns of # lint-amnesty, pylint: disable=line-too-long
courses.
In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format will get translated into
In the LMS/CMS, we have runtime link-rewriting, so at render time, this /static/... format will get translated into # lint-amnesty, pylint: disable=line-too-long
the actual /c4x/... path which the client needs to reference static content
"""
if location is not None:
@@ -123,7 +123,7 @@ class StaticContent(object):
return None
@staticmethod
def get_base_url_path_for_course_assets(course_key):
def get_base_url_path_for_course_assets(course_key): # lint-amnesty, pylint: disable=missing-function-docstring
if course_key is None:
return None
@@ -307,10 +307,10 @@ class StaticContent(object):
return url
class StaticContentStream(StaticContent):
def __init__(self, loc, name, content_type, stream, last_modified_at=None, thumbnail_location=None, import_path=None,
class StaticContentStream(StaticContent): # lint-amnesty, pylint: disable=missing-class-docstring
def __init__(self, loc, name, content_type, stream, last_modified_at=None, thumbnail_location=None, import_path=None, # lint-amnesty, pylint: disable=line-too-long
length=None, locked=False, content_digest=None):
super(StaticContentStream, self).__init__(loc, name, content_type, None, last_modified_at=last_modified_at,
super(StaticContentStream, self).__init__(loc, name, content_type, None, last_modified_at=last_modified_at, # lint-amnesty, pylint: disable=super-with-arguments
thumbnail_location=thumbnail_location, import_path=import_path,
length=length, locked=locked, content_digest=content_digest)
self._stream = stream
@@ -340,7 +340,7 @@ class StaticContentStream(StaticContent):
def close(self):
self._stream.close()
def copy_to_in_mem(self):
def copy_to_in_mem(self): # lint-amnesty, pylint: disable=missing-function-docstring
self._stream.seek(0)
content = StaticContent(self.location, self.name, self.content_type, self._stream.read(),
last_modified_at=self.last_modified_at, thumbnail_location=self.thumbnail_location,
@@ -469,4 +469,4 @@ class ContentStore(object):
Ensure that all appropriate indexes are created that are needed by this modulestore, or raise
an exception if unable to.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from importlib import import_module
@@ -18,7 +18,7 @@ def load_function(path):
return getattr(import_module(module_path), name)
def contentstore(name='default'):
def contentstore(name='default'): # lint-amnesty, pylint: disable=missing-function-docstring
if name not in _CONTENTSTORE:
class_ = load_function(settings.CONTENTSTORE['ENGINE'])
options = {}

View File

@@ -28,7 +28,7 @@ class MongoContentStore(ContentStore):
"""
MongoDB-backed ContentStore.
"""
# pylint: disable=unused-argument, bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value, unused-argument
def __init__(
self, host, db,
port=27017, tz_aware=True, user=None, password=None, bucket='fs', collection=None, **kwargs
@@ -92,8 +92,8 @@ class MongoContentStore(ContentStore):
# the location as the _id, we must delete before adding (there's no replace method in gridFS)
self.delete(content_id) # delete is a noop if the entry doesn't exist; so, don't waste time checking
thumbnail_location = content.thumbnail_location.to_deprecated_list_repr() if content.thumbnail_location else None
with self.fs.new_file(_id=content_id, filename=six.text_type(content.location), content_type=content.content_type,
thumbnail_location = content.thumbnail_location.to_deprecated_list_repr() if content.thumbnail_location else None # lint-amnesty, pylint: disable=line-too-long
with self.fs.new_file(_id=content_id, filename=six.text_type(content.location), content_type=content.content_type, # lint-amnesty, pylint: disable=line-too-long
displayname=content.name, content_son=content_son,
thumbnail_location=thumbnail_location,
import_path=content.import_path,
@@ -127,7 +127,7 @@ class MongoContentStore(ContentStore):
self.fs.delete(location_or_id)
@autoretry_read()
def find(self, location, throw_on_not_found=True, as_stream=False):
def find(self, location, throw_on_not_found=True, as_stream=False): # lint-amnesty, pylint: disable=arguments-differ
content_id, __ = self.asset_db_key(location)
try:
@@ -135,8 +135,8 @@ class MongoContentStore(ContentStore):
fp = self.fs.get(content_id)
# Need to replace dict IDs with SON for chunk lookup to work under Python 3
# because field order can be different and mongo cares about the order
if isinstance(fp._id, dict):
fp._file['_id'] = content_id
if isinstance(fp._id, dict): # lint-amnesty, pylint: disable=protected-access
fp._file['_id'] = content_id # lint-amnesty, pylint: disable=protected-access
thumbnail_location = getattr(fp, 'thumbnail_location', None)
if thumbnail_location:
thumbnail_location = location.course_key.make_asset_key(
@@ -154,8 +154,8 @@ class MongoContentStore(ContentStore):
with self.fs.get(content_id) as fp:
# Need to replace dict IDs with SON for chunk lookup to work under Python 3
# because field order can be different and mongo cares about the order
if isinstance(fp._id, dict):
fp._file['_id'] = content_id
if isinstance(fp._id, dict): # lint-amnesty, pylint: disable=protected-access
fp._file['_id'] = content_id # lint-amnesty, pylint: disable=protected-access
thumbnail_location = getattr(fp, 'thumbnail_location', None)
if thumbnail_location:
thumbnail_location = location.course_key.make_asset_key(
@@ -170,12 +170,12 @@ class MongoContentStore(ContentStore):
content_digest=getattr(fp, 'md5', None),
)
except NoFile:
if throw_on_not_found:
raise NotFoundError(content_id)
if throw_on_not_found: # lint-amnesty, pylint: disable=no-else-raise
raise NotFoundError(content_id) # lint-amnesty, pylint: disable=raise-missing-from
else:
return None
def export(self, location, output_directory):
def export(self, location, output_directory): # lint-amnesty, pylint: disable=missing-function-docstring
content = self.find(location)
filename = content.name
@@ -418,8 +418,8 @@ class MongoContentStore(ContentStore):
__, asset_key = self.asset_db_key(asset_key)
# Need to replace dict IDs with SON for chunk lookup to work under Python 3
# because field order can be different and mongo cares about the order
if isinstance(source_content._id, dict):
source_content._file['_id'] = asset_key.copy()
if isinstance(source_content._id, dict): # lint-amnesty, pylint: disable=protected-access
source_content._file['_id'] = asset_key.copy() # lint-amnesty, pylint: disable=protected-access
asset_key['org'] = dest_course_key.org
asset_key['course'] = dest_course_key.course
if getattr(dest_course_key, 'deprecated', False): # remove the run if exists

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from xmodule.contentstore.content import StaticContent
@@ -43,5 +43,5 @@ def restore_asset_from_trashcan(location):
try:
thumbnail_content = trash.find(content.thumbnail_location)
store.save(thumbnail_content)
except Exception:
except Exception: # lint-amnesty, pylint: disable=broad-except
pass # OK if this is left dangling

View File

@@ -202,7 +202,7 @@ def sorting_dates(start, advertised_start, announcement):
if start.tzinfo is None:
start = start.replace(tzinfo=utc)
except (TypeError, ValueError, AttributeError):
start = start
start = start # lint-amnesty, pylint: disable=self-assigning-variable
now = datetime.now(utc)

View File

@@ -20,10 +20,10 @@ from pytz import utc
from six import text_type
from xblock.fields import Boolean, Dict, Float, Integer, List, Scope, String
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers
from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers # lint-amnesty, pylint: disable=unused-import
from openedx.core.djangoapps.video_pipeline.models import VideoUploadsEnabledByDefault
from openedx.core.lib.license import LicenseMixin
from openedx.core.lib.teams_config import TeamsConfig, DEFAULT_COURSE_RUN_MAX_TEAM_SIZE
from openedx.core.lib.teams_config import TeamsConfig, DEFAULT_COURSE_RUN_MAX_TEAM_SIZE # lint-amnesty, pylint: disable=unused-import
from xmodule import course_metadata_utils
from xmodule.course_metadata_utils import DEFAULT_GRADING_POLICY, DEFAULT_START_DATE
from xmodule.graders import grader_from_conf
@@ -58,14 +58,14 @@ COURSE_VISIBILITY_PUBLIC_OUTLINE = 'public_outline'
COURSE_VISIBILITY_PUBLIC = 'public'
class StringOrDate(Date):
def from_json(self, value):
class StringOrDate(Date): # lint-amnesty, pylint: disable=missing-class-docstring
def from_json(self, value): # lint-amnesty, pylint: disable=arguments-differ
"""
Parse an optional metadata key containing a time or a string:
if present, assume it's a string if it doesn't parse.
"""
try:
result = super(StringOrDate, self).from_json(value)
result = super(StringOrDate, self).from_json(value) # lint-amnesty, pylint: disable=super-with-arguments
except ValueError:
return value
if result is None:
@@ -78,8 +78,8 @@ class StringOrDate(Date):
Convert a time struct or string to a string.
"""
try:
result = super(StringOrDate, self).to_json(value)
except:
result = super(StringOrDate, self).to_json(value) # lint-amnesty, pylint: disable=super-with-arguments
except: # lint-amnesty, pylint: disable=bare-except
return value
if result is None:
return value
@@ -105,7 +105,7 @@ edx_xml_parser = etree.XMLParser(dtd_validation=False, load_dtd=False,
_cached_toc = {}
class Textbook(object):
class Textbook(object): # lint-amnesty, pylint: disable=missing-class-docstring
def __init__(self, title, book_url):
self.title = title
self.book_url = book_url
@@ -115,7 +115,7 @@ class Textbook(object):
return int(self.table_of_contents[0].attrib['page'])
@lazy
def end_page(self):
def end_page(self): # lint-amnesty, pylint: disable=missing-function-docstring
# The last page should be the last element in the table of contents,
# but it may be nested. So recurse all the way down the last element
last_el = self.table_of_contents[-1]
@@ -148,7 +148,7 @@ class Textbook(object):
# expire every 10 minutes
if age.seconds < 600:
return table_of_contents
except Exception as err:
except Exception as err: # lint-amnesty, pylint: disable=broad-except
pass
# Get the table of contents from S3
@@ -158,7 +158,7 @@ class Textbook(object):
except Exception as err:
msg = 'Error %s: Unable to retrieve textbook table of contents at %s' % (err, toc_url)
log.error(msg)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
# TOC is XML. Parse it
try:
@@ -166,7 +166,7 @@ class Textbook(object):
except Exception as err:
msg = 'Error %s: Unable to parse XML for textbook table of contents at %s' % (err, toc_url)
log.error(msg)
raise Exception(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
return table_of_contents
@@ -178,13 +178,13 @@ class Textbook(object):
return not self == other
class TextbookList(List):
def from_json(self, values):
class TextbookList(List): # lint-amnesty, pylint: disable=missing-class-docstring
def from_json(self, values): # lint-amnesty, pylint: disable=arguments-differ
textbooks = []
for title, book_url in values:
try:
textbooks.append(Textbook(title, book_url))
except:
except: # lint-amnesty, pylint: disable=bare-except
# If we can't get to S3 (e.g. on a train with no internet), don't break
# the rest of the courseware.
log.exception("Couldn't load textbook ({0}, {1})".format(title, book_url))
@@ -192,7 +192,7 @@ class TextbookList(List):
return textbooks
def to_json(self, values):
def to_json(self, values): # lint-amnesty, pylint: disable=arguments-differ
json_data = []
for val in values:
if isinstance(val, Textbook):
@@ -215,7 +215,7 @@ class ProctoringProvider(String):
and include any inherited values from the platform default.
"""
errors = []
value = super(ProctoringProvider, self).from_json(value)
value = super(ProctoringProvider, self).from_json(value) # lint-amnesty, pylint: disable=super-with-arguments
provider_errors = self._validate_proctoring_provider(value)
errors.extend(provider_errors)
@@ -265,7 +265,7 @@ class ProctoringProvider(String):
"""
Return default value for ProctoringProvider.
"""
default = super(ProctoringProvider, self).default
default = super(ProctoringProvider, self).default # lint-amnesty, pylint: disable=super-with-arguments
proctoring_backend_settings = getattr(settings, 'PROCTORING_BACKENDS', None)
@@ -275,7 +275,7 @@ class ProctoringProvider(String):
return default
def get_available_providers():
def get_available_providers(): # lint-amnesty, pylint: disable=missing-function-docstring
proctoring_backend_settings = getattr(
settings,
'PROCTORING_BACKENDS',
@@ -314,7 +314,7 @@ class TeamsConfigField(Dict):
return value.cleaned_data
class CourseFields(object):
class CourseFields(object): # lint-amnesty, pylint: disable=missing-class-docstring
lti_passports = List(
display_name=_("LTI Passports"),
help=_('Enter the passports for course LTI tools in the following format: "id:client_key:client_secret".'),
@@ -1051,7 +1051,7 @@ class CourseDescriptor(CourseFields, SequenceDescriptor, LicenseMixin):
"""
Expects the same arguments as XModuleDescriptor.__init__
"""
super(CourseDescriptor, self).__init__(*args, **kwargs)
super(CourseDescriptor, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
_ = self.runtime.service(self, "i18n").ugettext
self._gating_prerequisites = None
@@ -1087,7 +1087,7 @@ class CourseDescriptor(CourseFields, SequenceDescriptor, LicenseMixin):
if not getattr(self, "tabs", []):
CourseTabList.initialize_default(self)
except InvalidTabsException as err:
raise type(err)('{msg} For course: {course_id}'.format(msg=text_type(err), course_id=six.text_type(self.id)))
raise type(err)('{msg} For course: {course_id}'.format(msg=text_type(err), course_id=six.text_type(self.id))) # lint-amnesty, pylint: disable=line-too-long
self.set_default_certificate_available_date()
@@ -1197,11 +1197,11 @@ class CourseDescriptor(CourseFields, SequenceDescriptor, LicenseMixin):
return definition, children
def definition_to_xml(self, resource_fs):
xml_object = super(CourseDescriptor, self).definition_to_xml(resource_fs)
xml_object = super(CourseDescriptor, self).definition_to_xml(resource_fs) # lint-amnesty, pylint: disable=super-with-arguments
if self.textbooks:
textbook_xml_object = etree.Element('textbook')
for textbook in self.textbooks:
for textbook in self.textbooks: # lint-amnesty, pylint: disable=not-an-iterable
textbook_xml_object.set('title', textbook.title)
textbook_xml_object.set('book_url', textbook.book_url)
@@ -1245,7 +1245,7 @@ class CourseDescriptor(CourseFields, SequenceDescriptor, LicenseMixin):
return grader_from_conf(self.raw_grader)
@property
def raw_grader(self):
def raw_grader(self): # lint-amnesty, pylint: disable=missing-function-docstring
# force the caching of the xblock value so that it can detect the change
# pylint: disable=pointless-statement
self.grading_policy['GRADER']

View File

@@ -32,7 +32,7 @@ class EditingMixin(EditingFields, MakoTemplateBlockBase):
"""
`data` should not be editable in the Studio settings editor.
"""
non_editable_fields = super(EditingMixin, self).non_editable_metadata_fields
non_editable_fields = super(EditingMixin, self).non_editable_metadata_fields # lint-amnesty, pylint: disable=super-with-arguments
non_editable_fields.append(self.fields['data'])
return non_editable_fields
@@ -46,7 +46,7 @@ class EditingMixin(EditingFields, MakoTemplateBlockBase):
return _context
class EditingDescriptor(EditingMixin, MakoModuleDescriptor):
class EditingDescriptor(EditingMixin, MakoModuleDescriptor): # lint-amnesty, pylint: disable=abstract-method
pass
@@ -72,7 +72,7 @@ class TabsEditingMixin(EditingFields, MakoTemplateBlockBase):
return _context
@classmethod
def get_css(cls):
def get_css(cls): # lint-amnesty, pylint: disable=missing-function-docstring
# load every tab's css
for tab in cls.tabs:
tab_styles = tab.get('css', {})
@@ -84,7 +84,7 @@ class TabsEditingMixin(EditingFields, MakoTemplateBlockBase):
return cls.css
class TabsEditingDescriptor(TabsEditingMixin, MakoModuleDescriptor):
class TabsEditingDescriptor(TabsEditingMixin, MakoModuleDescriptor): # lint-amnesty, pylint: disable=abstract-method
"""
Module that provides a raw editing view of its data and children. It does not
perform any validation on its definition---just passes it along to the browser.
@@ -95,10 +95,10 @@ class TabsEditingDescriptor(TabsEditingMixin, MakoModuleDescriptor):
template to be always loaded, so don't forget to include
settings tab in your module descriptor.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class XMLEditingDescriptor(EditingDescriptor):
class XMLEditingDescriptor(EditingDescriptor): # lint-amnesty, pylint: disable=abstract-method
"""
Module that provides a raw editing view of its data as XML. It does not perform
any validation of its definition
@@ -110,7 +110,7 @@ class XMLEditingDescriptor(EditingDescriptor):
js_module_name = "XMLEditingDescriptor"
class MetadataOnlyEditingDescriptor(EditingDescriptor):
class MetadataOnlyEditingDescriptor(EditingDescriptor): # lint-amnesty, pylint: disable=abstract-method
"""
Module which only provides an editing interface for the metadata, it does
not expose a UI for editing the module data
@@ -122,7 +122,7 @@ class MetadataOnlyEditingDescriptor(EditingDescriptor):
mako_template = "widgets/metadata-only-edit.html"
class JSONEditingDescriptor(EditingDescriptor):
class JSONEditingDescriptor(EditingDescriptor): # lint-amnesty, pylint: disable=abstract-method
"""
Module that provides a raw editing view of its data as XML. It does not perform
any validation of its definition

View File

@@ -128,7 +128,7 @@ class ErrorBlock(
}
@classmethod
def from_json(cls, json_data, system, location, error_msg='Error not available'):
def from_json(cls, json_data, system, location, error_msg='Error not available'): # lint-amnesty, pylint: disable=missing-function-docstring
try:
json_string = json.dumps(json_data, skipkeys=False, indent=4, cls=EdxJSONEncoder)
except: # pylint: disable=bare-except

View File

@@ -80,6 +80,6 @@ def make_error_tracker():
return ErrorLog(error_tracker, errors)
def null_error_tracker(msg):
def null_error_tracker(msg): # lint-amnesty, pylint: disable=unused-argument
'''A dummy error tracker that just ignores the messages'''
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -1,4 +1,4 @@
class InvalidDefinitionError(Exception):
class InvalidDefinitionError(Exception): # lint-amnesty, pylint: disable=missing-module-docstring
pass
@@ -11,7 +11,7 @@ class ProcessingError(Exception):
An error occurred while processing a request to the XModule.
For example: if an exception occurs while checking a capa problem.
'''
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class InvalidVersionError(Exception):
@@ -20,7 +20,7 @@ class InvalidVersionError(Exception):
for a non-leaf node)
"""
def __init__(self, location):
super(InvalidVersionError, self).__init__()
super(InvalidVersionError, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.location = location
@@ -29,7 +29,7 @@ class SerializationError(Exception):
Thrown when a module cannot be exported to XML
"""
def __init__(self, location, msg):
super(SerializationError, self).__init__(msg)
super(SerializationError, self).__init__(msg) # lint-amnesty, pylint: disable=super-with-arguments
self.location = location
@@ -37,7 +37,7 @@ class UndefinedContext(Exception):
"""
Tried to access an xmodule field which needs a different context (runtime) to have a value.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class HeartbeatFailure(Exception):
@@ -50,4 +50,4 @@ class HeartbeatFailure(Exception):
In addition to a msg, provide the name of the service.
"""
self.service = service
super(HeartbeatFailure, self).__init__(msg)
super(HeartbeatFailure, self).__init__(msg) # lint-amnesty, pylint: disable=super-with-arguments

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import datetime
import logging
@@ -43,7 +43,7 @@ class Date(JSONField):
result = result.replace(tzinfo=UTC)
return result
def from_json(self, field):
def from_json(self, field): # lint-amnesty, pylint: disable=arguments-differ
"""
Parse an optional metadata key containing a time: if present, complain
if it doesn't parse.
@@ -55,7 +55,7 @@ class Date(JSONField):
return None
elif isinstance(field, six.string_types):
return self._parse_date_wo_default_month_day(field)
elif isinstance(field, six.integer_types) or isinstance(field, float):
elif isinstance(field, six.integer_types) or isinstance(field, float): # lint-amnesty, pylint: disable=consider-merging-isinstance
return datetime.datetime.fromtimestamp(field / 1000, UTC)
elif isinstance(field, time.struct_time):
return datetime.datetime.fromtimestamp(time.mktime(field), UTC)
@@ -90,14 +90,14 @@ class Date(JSONField):
enforce_type = from_json
TIMEDELTA_REGEX = re.compile(r'^((?P<days>\d+?) day(?:s?))?(\s)?((?P<hours>\d+?) hour(?:s?))?(\s)?((?P<minutes>\d+?) minute(?:s)?)?(\s)?((?P<seconds>\d+?) second(?:s)?)?$')
TIMEDELTA_REGEX = re.compile(r'^((?P<days>\d+?) day(?:s?))?(\s)?((?P<hours>\d+?) hour(?:s?))?(\s)?((?P<minutes>\d+?) minute(?:s)?)?(\s)?((?P<seconds>\d+?) second(?:s)?)?$') # lint-amnesty, pylint: disable=line-too-long
class Timedelta(JSONField):
class Timedelta(JSONField): # lint-amnesty, pylint: disable=missing-class-docstring
# Timedeltas are immutable, see http://docs.python.org/2/library/datetime.html#available-types
MUTABLE = False
def from_json(self, time_str):
def from_json(self, time_str): # lint-amnesty, pylint: disable=arguments-differ
"""
time_str: A string with the following components:
<D> day[s] (optional)
@@ -177,7 +177,7 @@ class RelativeTime(JSONField):
try:
obj_time = time.strptime(value, '%H:%M:%S')
except ValueError as e:
raise ValueError(
raise ValueError( # lint-amnesty, pylint: disable=raise-missing-from
"Incorrect RelativeTime value {!r} was set in XML or serialized. "
"Original parse message is {}".format(value, text_type(e))
)
@@ -290,7 +290,7 @@ class ScoreField(JSONField):
)
)
if not (0 <= raw_earned <= raw_possible):
if not (0 <= raw_earned <= raw_possible): # lint-amnesty, pylint: disable=superfluous-parens
raise ValueError(
'Error deserializing field of type {0}: Expected raw_earned between 0 and {1}, got {2}.'.format(
self.display_name,

View File

@@ -78,7 +78,7 @@ class ProblemScore(ScoreBase):
:param weight: Weight of this problem
:type weight: int|float|None
"""
super(ProblemScore, self).__init__(*args, **kwargs)
super(ProblemScore, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.raw_earned = float(raw_earned) if raw_earned is not None else None
self.raw_possible = float(raw_possible) if raw_possible is not None else None
self.earned = float(weighted_earned) if weighted_earned is not None else None
@@ -101,7 +101,7 @@ class AggregatedScore(ScoreBase):
:param tw_possible: Total aggregated sum of all weighted possible values
:type tw_possible: int|float|None
"""
super(AggregatedScore, self).__init__(*args, **kwargs)
super(AggregatedScore, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.earned = float(tw_earned) if tw_earned is not None else None
self.possible = float(tw_possible) if tw_possible is not None else None
@@ -264,7 +264,7 @@ class WeightedSubsectionsGrader(CourseGrader):
self.subgraders = subgraders
@property
def sum_of_weights(self):
def sum_of_weights(self): # lint-amnesty, pylint: disable=missing-function-docstring
result = 0
for _, _, weight in self.subgraders:
result += weight
@@ -333,7 +333,7 @@ class AssignmentFormatGrader(CourseGrader):
min_count = 2 would produce the labels "Assignment 3", "Assignment 4"
"""
def __init__(
def __init__( # lint-amnesty, pylint: disable=super-init-not-called
self,
type, # pylint: disable=redefined-builtin
min_count,

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
from lxml import etree

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import copy
import logging
@@ -43,7 +43,7 @@ _ = lambda text: text
@XBlock.needs("i18n")
class HtmlBlockMixin(
class HtmlBlockMixin( # lint-amnesty, pylint: disable=abstract-method
XmlMixin, EditingMixin,
XModuleDescriptorToXBlockMixin, XModuleToXBlockMixin, HTMLSnippet, ResourceTemplates, XModuleMixin,
):
@@ -223,7 +223,7 @@ class HtmlBlockMixin(
# snippets that will be included in the middle of pages.
@classmethod
def load_definition(cls, xml_object, system, location, id_generator):
def load_definition(cls, xml_object, system, location, id_generator): # lint-amnesty, pylint: disable=arguments-differ
'''Load a descriptor from the specified xml_object:
If there is a filename attribute, load it as a string, and
@@ -341,12 +341,12 @@ class HtmlBlockMixin(
"""
`use_latex_compiler` should not be editable in the Studio settings editor.
"""
non_editable_fields = super(HtmlBlockMixin, self).non_editable_metadata_fields
non_editable_fields = super(HtmlBlockMixin, self).non_editable_metadata_fields # lint-amnesty, pylint: disable=super-with-arguments
non_editable_fields.append(HtmlBlockMixin.use_latex_compiler)
return non_editable_fields
def index_dictionary(self):
xblock_body = super(HtmlBlockMixin, self).index_dictionary()
xblock_body = super(HtmlBlockMixin, self).index_dictionary() # lint-amnesty, pylint: disable=super-with-arguments
# Removing script and style
html_content = re.sub(
re.compile(
@@ -373,14 +373,14 @@ class HtmlBlockMixin(
@edxnotes
class HtmlBlock(HtmlBlockMixin):
class HtmlBlock(HtmlBlockMixin): # lint-amnesty, pylint: disable=abstract-method
"""
This is the actual HTML XBlock.
Nothing extra is required; this is just a wrapper to include edxnotes support.
"""
class AboutFields(object):
class AboutFields(object): # lint-amnesty, pylint: disable=missing-class-docstring
display_name = String(
help=_("The display name for this component."),
scope=Scope.settings,
@@ -394,7 +394,7 @@ class AboutFields(object):
@XBlock.tag("detached")
class AboutBlock(AboutFields, HtmlBlockMixin):
class AboutBlock(AboutFields, HtmlBlockMixin): # lint-amnesty, pylint: disable=abstract-method
"""
These pieces of course content are treated as HtmlBlocks but we need to overload where the templates are located
in order to be able to create new ones
@@ -429,7 +429,7 @@ class StaticTabFields(object):
@XBlock.tag("detached")
class StaticTabBlock(StaticTabFields, HtmlBlockMixin):
class StaticTabBlock(StaticTabFields, HtmlBlockMixin): # lint-amnesty, pylint: disable=abstract-method
"""
These pieces of course content are treated as HtmlBlocks but we need to overload where the templates are located
in order to be able to create new ones
@@ -454,7 +454,7 @@ class CourseInfoFields(object):
@XBlock.tag("detached")
class CourseInfoBlock(CourseInfoFields, HtmlBlockMixin):
class CourseInfoBlock(CourseInfoFields, HtmlBlockMixin): # lint-amnesty, pylint: disable=abstract-method
"""
These pieces of course content are treated as HtmlBlock but we need to overload where the templates are located
in order to be able to create new ones
@@ -485,7 +485,7 @@ class CourseInfoBlock(CourseInfoFields, HtmlBlockMixin):
return self.system.render_template("{0}/course_updates.html".format(self.TEMPLATE_DIR), context)
@classmethod
def order_updates(self, updates):
def order_updates(self, updates): # lint-amnesty, pylint: disable=bad-classmethod-argument
"""
Returns any course updates in reverse chronological order.
"""

View File

@@ -345,7 +345,7 @@ class LibraryContentBlock(
for block_type, block_id in self.selected_children():
yield self.runtime.get_block(self.location.course_key.make_usage_key(block_type, block_id))
def student_view(self, context):
def student_view(self, context): # lint-amnesty, pylint: disable=missing-function-docstring
fragment = Fragment()
contents = []
child_context = {} if not context else copy(context)
@@ -454,7 +454,7 @@ class LibraryContentBlock(
return user_id
@XBlock.handler
def refresh_children(self, request=None, suffix=None):
def refresh_children(self, request=None, suffix=None): # lint-amnesty, pylint: disable=unused-argument
"""
Refresh children:
This method is to be used when any of the libraries that this block
@@ -634,7 +634,7 @@ class LibraryContentBlock(
values = [{"display_name": name, "value": six.text_type(key)} for key, name in all_libraries]
return values
def editor_saved(self, user, old_metadata, old_content):
def editor_saved(self, user, old_metadata, old_content): # lint-amnesty, pylint: disable=unused-argument
"""
If source_library_id or capa_type has been edited, refresh_children automatically.
"""

View File

@@ -4,7 +4,7 @@ XBlock runtime services for LibraryContentBlock
import hashlib
import six
from django.contrib.auth.models import User
from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user
from django.core.exceptions import PermissionDenied
from opaque_keys.edx.keys import UsageKey
from opaque_keys.edx.locator import LibraryLocator, LibraryUsageLocator, LibraryUsageLocatorV2, BlockUsageLocator

View File

@@ -27,7 +27,7 @@ LTI_2_0_JSON_CONTENT_TYPE = 'application/vnd.ims.lis.v2.result+json'
class LTIError(Exception):
"""Error class for LTIModule and LTI20ModuleMixin"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class LTI20ModuleMixin(object):
@@ -295,7 +295,7 @@ class LTI20ModuleMixin(object):
self.verify_oauth_body_sign(request, content_type=LTI_2_0_JSON_CONTENT_TYPE)
except (ValueError, LTIError) as err:
log.info("[LTI]: v2.0 result service -- OAuth body verification failed: {}".format(text_type(err)))
raise LTIError(text_type(err))
raise LTIError(text_type(err)) # lint-amnesty, pylint: disable=raise-missing-from
def parse_lti_2_0_result_json(self, json_str):
"""
@@ -322,7 +322,7 @@ class LTI20ModuleMixin(object):
except (ValueError, TypeError):
msg = "Supplied JSON string in request body could not be decoded: {}".format(json_str)
log.info("[LTI] {}".format(msg))
raise LTIError(msg)
raise LTIError(msg) # lint-amnesty, pylint: disable=raise-missing-from
# the standard supports a list of objects, who knows why. It must contain at least 1 element, and the
# first element must be a dict
@@ -366,6 +366,6 @@ class LTI20ModuleMixin(object):
except (TypeError, ValueError) as err:
msg = "Could not convert resultScore to float: {}".format(text_type(err))
log.info("[LTI] {}".format(msg))
raise LTIError(msg)
raise LTIError(msg) # lint-amnesty, pylint: disable=raise-missing-from
return score, json_obj.get('comment', "")

View File

@@ -213,7 +213,7 @@ class LTIFields(object):
)
# Users will be presented with a message indicating that their e-mail/username would be sent to a third
# party application. When "Open in New Page" is not selected, the tool automatically appears without any user action.
# party application. When "Open in New Page" is not selected, the tool automatically appears without any user action. # lint-amnesty, pylint: disable=line-too-long
ask_to_send_username = Boolean(
display_name=_("Request user's username"),
# Translators: This is used to request the user's username for a third party service.
@@ -232,7 +232,7 @@ class LTIFields(object):
description = String(
display_name=_("LTI Application Information"),
help=_(
"Enter a description of the third party application. If requesting username and/or email, use this text box to inform users "
"Enter a description of the third party application. If requesting username and/or email, use this text box to inform users " # lint-amnesty, pylint: disable=line-too-long
"why their username and/or email will be forwarded to a third party application."
),
default="",
@@ -347,7 +347,7 @@ class LTIModule(LTIFields, LTI20ModuleMixin, XModule):
css = {'scss': [resource_string(__name__, 'css/lti/lti.scss')]}
js_module_name = 'LTI'
def get_input_fields(self):
def get_input_fields(self): # lint-amnesty, pylint: disable=missing-function-docstring
# LTI provides a list of default parameters that might be passed as
# part of the POST data. These parameters should not be prefixed.
# Likewise, The creator of an LTI link can add custom key/value parameters
@@ -397,7 +397,7 @@ class LTIModule(LTIFields, LTI20ModuleMixin, XModule):
msg = _('Could not parse custom parameter: {custom_parameter}. Should be "x=y" string.').format(
custom_parameter="{0!r}".format(custom_parameter)
)
raise LTIError(msg)
raise LTIError(msg) # lint-amnesty, pylint: disable=raise-missing-from
# LTI specs: 'custom_' should be prepended before each custom parameter, as pointed in link above.
if param_name not in PARAMETERS:
@@ -512,7 +512,7 @@ class LTIModule(LTIFields, LTI20ModuleMixin, XModule):
i4x-2-3-lti-31de800015cf4afb973356dbe81496df this part of resource_link_id:
makes resource_link_id to be unique among courses inside same system.
"""
return six.text_type(six.moves.urllib.parse.quote("{}-{}".format(self.system.hostname, self.location.html_id())))
return six.text_type(six.moves.urllib.parse.quote("{}-{}".format(self.system.hostname, self.location.html_id()))) # lint-amnesty, pylint: disable=line-too-long
def get_lis_result_sourcedid(self):
"""
@@ -599,8 +599,8 @@ class LTIModule(LTIFields, LTI20ModuleMixin, XModule):
u'lis_outcome_service_url': self.get_outcome_service_url()
})
self.user_email = ""
self.user_username = ""
self.user_email = "" # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.user_username = "" # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Username and email can't be sent in studio mode, because the user object is not defined.
# To test functionality test in LMS
@@ -608,13 +608,13 @@ class LTIModule(LTIFields, LTI20ModuleMixin, XModule):
if callable(self.runtime.get_real_user):
real_user_object = self.runtime.get_real_user(self.runtime.anonymous_student_id)
try:
self.user_email = real_user_object.email
self.user_email = real_user_object.email # lint-amnesty, pylint: disable=attribute-defined-outside-init
except AttributeError:
self.user_email = ""
self.user_email = "" # lint-amnesty, pylint: disable=attribute-defined-outside-init
try:
self.user_username = real_user_object.username
self.user_username = real_user_object.username # lint-amnesty, pylint: disable=attribute-defined-outside-init
except AttributeError:
self.user_username = ""
self.user_username = "" # lint-amnesty, pylint: disable=attribute-defined-outside-init
if self.ask_to_send_username and self.user_username:
body["lis_person_sourcedid"] = self.user_username
@@ -661,14 +661,14 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
# so '='' becomes '%3D'.
# We send form via browser, so browser will encode it again,
# So we need to decode signature back:
params[u'oauth_signature'] = six.moves.urllib.parse.unquote(params[u'oauth_signature']).encode('utf-8').decode('utf8')
params[u'oauth_signature'] = six.moves.urllib.parse.unquote(params[u'oauth_signature']).encode('utf-8').decode('utf8') # lint-amnesty, pylint: disable=line-too-long
# Add LTI parameters to OAuth parameters for sending in form.
params.update(body)
return params
@XBlock.handler
def grade_handler(self, request, suffix):
def grade_handler(self, request, suffix): # lint-amnesty, pylint: disable=unused-argument
"""
This is called by courseware.module_render, to handle an AJAX call.
@@ -749,9 +749,9 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
try:
imsx_messageIdentifier, sourcedId, score, action = self.parse_grade_xml_body(request.body)
except Exception as e:
except Exception as e: # lint-amnesty, pylint: disable=broad-except
error_message = "Request body XML parsing error: " + escape(text_type(e))
log.debug("[LTI]: " + error_message)
log.debug("[LTI]: " + error_message) # lint-amnesty, pylint: disable=logging-not-lazy
failure_values['imsx_description'] = error_message
return Response(response_xml_template.format(**failure_values), content_type="application/xml")
@@ -762,7 +762,7 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
failure_values['imsx_messageIdentifier'] = escape(imsx_messageIdentifier)
error_message = "OAuth verification error: " + escape(text_type(e))
failure_values['imsx_description'] = error_message
log.debug("[LTI]: " + error_message)
log.debug("[LTI]: " + error_message) # lint-amnesty, pylint: disable=logging-not-lazy
return Response(response_xml_template.format(**failure_values), content_type="application/xml")
real_user = self.system.get_real_user(six.moves.urllib.parse.unquote(sourcedId.split(':')[-1]))
@@ -808,7 +808,7 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
imsx_messageIdentifier = root.xpath("//def:imsx_messageIdentifier", namespaces=namespaces)[0].text or ''
sourcedId = root.xpath("//def:sourcedId", namespaces=namespaces)[0].text
score = root.xpath("//def:textString", namespaces=namespaces)[0].text
action = root.xpath("//def:imsx_POXBody", namespaces=namespaces)[0].getchildren()[0].tag.replace('{' + lti_spec_namespace + '}', '')
action = root.xpath("//def:imsx_POXBody", namespaces=namespaces)[0].getchildren()[0].tag.replace('{' + lti_spec_namespace + '}', '') # lint-amnesty, pylint: disable=line-too-long
# Raise exception if score is not float or not in range 0.0-1.0 regarding spec.
score = float(score)
if not 0 <= score <= 1:
@@ -832,7 +832,7 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
LTIError if request is incorrect.
"""
client_key, client_secret = self.get_client_key_secret()
client_key, client_secret = self.get_client_key_secret() # lint-amnesty, pylint: disable=unused-variable
headers = {
'Authorization': six.text_type(request.headers.get('Authorization')),
'Content-Type': content_type,
@@ -891,7 +891,7 @@ oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
msg = _('Could not parse LTI passport: {lti_passport}. Should be "id:key:secret" string.').format(
lti_passport='{0!r}'.format(lti_passport)
)
raise LTIError(msg)
raise LTIError(msg) # lint-amnesty, pylint: disable=raise-missing-from
if lti_id == self.lti_id.strip():
return key, secret

View File

@@ -8,9 +8,9 @@ from web_fragments.fragment import Fragment
from .x_module import DescriptorSystem, XModuleDescriptor, shim_xmodule_js
class MakoDescriptorSystem(DescriptorSystem):
class MakoDescriptorSystem(DescriptorSystem): # lint-amnesty, pylint: disable=abstract-method
def __init__(self, render_template, **kwargs):
super(MakoDescriptorSystem, self).__init__(**kwargs)
super(MakoDescriptorSystem, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.render_template = render_template
@@ -27,7 +27,7 @@ class MakoTemplateBlockBase(object):
# pylint: disable=no-member
def __init__(self, *args, **kwargs):
super(MakoTemplateBlockBase, self).__init__(*args, **kwargs)
super(MakoTemplateBlockBase, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
if getattr(self.runtime, 'render_template', None) is None:
raise TypeError(
'{runtime} must have a render_template function'

View File

@@ -80,7 +80,7 @@ class ModuleStoreEnum(object):
class Branch(object):
"""
Branch constants to use for stores, such as Mongo, that have only 2 branches: DRAFT and PUBLISHED
Note: These values are taken from server configuration settings, so should not be changed without alerting DevOps
Note: These values are taken from server configuration settings, so should not be changed without alerting DevOps # lint-amnesty, pylint: disable=line-too-long
"""
draft_preferred = 'draft-preferred'
published_only = 'published-only'
@@ -161,7 +161,7 @@ class ActiveBulkThread(threading.local):
Add the expected vars to the thread.
"""
def __init__(self, bulk_ops_record_type, **kwargs):
super(ActiveBulkThread, self).__init__(**kwargs)
super(ActiveBulkThread, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.records = defaultdict(bulk_ops_record_type)
@@ -178,7 +178,7 @@ class BulkOperationsMixin(object):
mongo_connection.
"""
def __init__(self, *args, **kwargs):
super(BulkOperationsMixin, self).__init__(*args, **kwargs)
super(BulkOperationsMixin, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self._active_bulk_ops = ActiveBulkThread(self._bulk_ops_record_type)
self.signal_handler = None
@@ -211,7 +211,7 @@ class BulkOperationsMixin(object):
if ignore_case:
for key, record in six.iteritems(self._active_bulk_ops.records):
# Shortcut: check basic equivalence for cases where org/course/run might be None.
if (key == course_key) or (
if (key == course_key) or ( # lint-amnesty, pylint: disable=too-many-boolean-expressions
(key.org and key.org.lower() == course_key.org.lower()) and
(key.course and key.course.lower() == course_key.course.lower()) and
(key.run and key.run.lower() == course_key.run.lower())
@@ -242,7 +242,7 @@ class BulkOperationsMixin(object):
Implementing classes must override this method; otherwise, the bulk operations are a noop
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def _begin_bulk_operation(self, course_key, ignore_case=False):
"""
@@ -264,7 +264,7 @@ class BulkOperationsMixin(object):
Implementing classes must override this method; otherwise, the bulk operations are a noop
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def _end_bulk_operation(self, structure_key, emit_signals=True, ignore_case=False):
"""
@@ -288,7 +288,7 @@ class BulkOperationsMixin(object):
if bulk_ops_record.active:
return
dirty = self._end_outermost_bulk_operation(bulk_ops_record, structure_key)
dirty = self._end_outermost_bulk_operation(bulk_ops_record, structure_key) # lint-amnesty, pylint: disable=assignment-from-no-return
# The bulk op has ended. However, the signal tasks below still need to use the
# built-up bulk op information (if the signals trigger tasks in the same thread).
@@ -387,7 +387,7 @@ class EditInfo(object):
self.original_usage_version = edit_info.get('original_usage_version', None)
def __repr__(self):
# pylint: disable=bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value
return ("{classname}(previous_version={self.previous_version}, "
"update_version={self.update_version}, "
"source_version={source_version}, "
@@ -400,7 +400,7 @@ class EditInfo(object):
self=self,
classname=self.__class__.__name__,
source_version="UNSET" if self.source_version is None else self.source_version,
) # pylint: disable=bad-continuation
) # lint-amnesty, pylint: disable=bad-continuation, bad-option-value
def __eq__(self, edit_info):
"""
@@ -474,7 +474,7 @@ class BlockData(object):
return self.asides
def __repr__(self):
# pylint: disable=bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value
return ("{classname}(fields={self.fields}, "
"block_type={self.block_type}, "
"definition={self.definition}, "
@@ -485,7 +485,7 @@ class BlockData(object):
self=self,
classname=self.__class__.__name__,
asides=self.get_asides()
) # pylint: disable=bad-continuation
) # lint-amnesty, pylint: disable=bad-continuation, bad-option-value
def __eq__(self, block_data):
"""
@@ -508,10 +508,10 @@ class IncorrectlySortedList(Exception):
"""
Thrown when calling find() on a SortedAssetList not sorted by filename.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class SortedAssetList(SortedKeyList):
class SortedAssetList(SortedKeyList): # lint-amnesty, pylint: disable=abstract-method
"""
List of assets that is sorted based on an asset attribute.
"""
@@ -521,7 +521,7 @@ class SortedAssetList(SortedKeyList):
if key_func is None:
kwargs['key'] = itemgetter('filename')
self.filename_sort = True
super(SortedAssetList, self).__init__(**kwargs)
super(SortedAssetList, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
@contract(asset_id=AssetKey)
def find(self, asset_id):
@@ -575,7 +575,7 @@ class ModuleStoreAssetBase(object):
- AssetMetadata[] for all assets of the given asset_key's type
- the index of asset in list (None if asset does not exist)
"""
course_assets = self._find_course_assets(asset_key.course_key)
course_assets = self._find_course_assets(asset_key.course_key) # lint-amnesty, pylint: disable=no-member
all_assets = SortedAssetList(iterable=course_assets.setdefault(asset_key.block_type, []))
idx = all_assets.find(asset_key)
@@ -605,7 +605,7 @@ class ModuleStoreAssetBase(object):
course_key='CourseKey', asset_type='None | str',
start='int | None', maxresults='int | None', sort='tuple(str,int) | None'
)
def get_all_asset_metadata(self, course_key, asset_type, start=0, maxresults=-1, sort=None, **kwargs):
def get_all_asset_metadata(self, course_key, asset_type, start=0, maxresults=-1, sort=None, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Returns a list of asset metadata for all assets of the given asset_type in the course.
@@ -622,7 +622,7 @@ class ModuleStoreAssetBase(object):
Returns:
List of AssetMetadata objects.
"""
course_assets = self._find_course_assets(course_key)
course_assets = self._find_course_assets(course_key) # lint-amnesty, pylint: disable=no-member
# Determine the proper sort - with defaults of ('displayname', SortOrder.ascending).
key_func = None
@@ -636,7 +636,7 @@ class ModuleStoreAssetBase(object):
if asset_type is None:
# Add assets of all types to the sorted list.
all_assets = SortedAssetList(iterable=[], key=key_func)
for asset_type, val in six.iteritems(course_assets):
for asset_type, val in six.iteritems(course_assets): # lint-amnesty, pylint: disable=redefined-argument-from-local
all_assets.update(val)
else:
# Add assets of a single type to the sorted list.
@@ -775,7 +775,7 @@ class ModuleStoreAssetWriteInterface(ModuleStoreAssetBase):
dest_course_key (CourseKey): identifier of course to copy to
user_id (int): user ID copying the asset metadata
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
@@ -789,7 +789,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
"""
Returns True if usage_key exists in this ModuleStore.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_item(self, usage_key, depth=0, using_descriptor_system=None, **kwargs):
@@ -809,7 +809,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
in the request. The depth is counted in the number of calls to
get_children() to cache. None indicates to cache all descendents
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_course_errors(self, course_key):
@@ -823,7 +823,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
Args:
course_key (:class:`.CourseKey`): The course to check for errors
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_items(self, course_id, qualifiers=None, **kwargs):
@@ -834,7 +834,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
location: Something that can be passed to Location
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@contract(block='XBlock | BlockData | dict', qualifiers=dict)
def _block_matches(self, block, qualifiers):
@@ -920,7 +920,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
This key may represent a course that doesn't exist in this modulestore.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def make_course_usage_key(self, course_key):
@@ -928,7 +928,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
Return a valid :class:`~opaque_keys.edx.keys.UsageKey` for this modulestore
that matches the supplied course_key.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_courses(self, **kwargs):
@@ -938,7 +938,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
will efficiently apply a filter so that only the courses of the specified
ORG in the CourseKey will be fetched.
'''
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_course(self, course_id, depth=0, **kwargs):
@@ -946,7 +946,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
Look for a specific course by its id (:class:`CourseKey`).
Returns the course descriptor, or None if not found.
'''
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def has_course(self, course_id, ignore_case=False, **kwargs):
@@ -957,7 +957,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
ignore_case (boolean): some modulestores are case-insensitive. Use this flag
to search for whether a potentially conflicting course exists in that case.
'''
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_parent_location(self, location, **kwargs):
@@ -965,7 +965,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
Find the location that is the parent of this location in this
course. Needed for path_to_location().
'''
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_orphans(self, course_key, **kwargs):
@@ -974,7 +974,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
usually orphaned. NOTE: may include xblocks which still have references via xblocks which don't
use children to point to their dependents.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_errored_courses(self):
@@ -982,7 +982,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
Return a dictionary of course_dir -> [(msg, exception_str)], for each
course_dir where course loading failed.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_modulestore_type(self, course_id):
@@ -990,7 +990,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
Returns a type which identifies which modulestore is servicing the given
course_id. The return can be either "xml" (for XML based courses) or "mongo" for MongoDB backed courses
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_courses_for_wiki(self, wiki_slug, **kwargs):
@@ -999,21 +999,21 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
:param wiki_slug: the course wiki root slug
:return: list of course keys
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def has_published_version(self, xblock):
"""
Returns true if this xblock exists in the published course regardless of whether it's up to date
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def close_connections(self):
"""
Closes any open connections to the underlying databases
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@contextmanager
def bulk_operations(self, course_id, emit_signals=True, ignore_case=False): # pylint: disable=unused-argument
@@ -1030,7 +1030,7 @@ class ModuleStoreRead(six.with_metaclass(ABCMeta, ModuleStoreAssetBase)):
This method is intended for use by tests and administrative commands, and not
to be run during server startup.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreAssetWriteInterface)):
@@ -1053,7 +1053,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
:raises VersionConflictError: if org, course, run, and version_guid given and the current
version head != version_guid and force is not True. (only applicable to version tracking stores)
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def delete_item(self, location, user_id, **kwargs):
@@ -1072,7 +1072,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
:raises VersionConflictError: if org, course, run, and version_guid given and the current
version head != version_guid and force is not True. (only applicable to version tracking stores)
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def create_course(self, org, course, run, user_id, fields=None, **kwargs):
@@ -1089,7 +1089,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
Returns: a CourseDescriptor
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def create_item(self, user_id, course_key, block_type, block_id=None, fields=None, **kwargs):
@@ -1108,7 +1108,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
fields (dict): A dictionary specifying initial values for some or all fields
in the newly created block
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def clone_course(self, source_course_id, dest_course_id, user_id, fields=None):
@@ -1125,7 +1125,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
ItemNotFoundError: if the source course doesn't exist (or any of its xblocks aren't found)
DuplicateItemError: if the destination course already exists (with content in some cases)
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def delete_course(self, course_key, user_id, **kwargs):
@@ -1137,7 +1137,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
course_key (CourseKey): which course to delete
user_id: id of the user deleting the course
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def _drop_database(self, database=True, collections=True, connections=True):
@@ -1152,7 +1152,7 @@ class ModuleStoreWrite(six.with_metaclass(ABCMeta, ModuleStoreRead, ModuleStoreA
If connections is True, then close the connection to the database as well.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
# pylint: disable=abstract-method
@@ -1163,18 +1163,18 @@ class ModuleStoreReadBase(BulkOperationsMixin, ModuleStoreRead):
def __init__(
self,
contentstore=None,
doc_store_config=None, # ignore if passed up
doc_store_config=None, # ignore if passed up # lint-amnesty, pylint: disable=unused-argument
metadata_inheritance_cache_subsystem=None, request_cache=None,
xblock_mixins=(), xblock_select=None, xblock_field_data_wrappers=(), disabled_xblock_types=lambda: [], # pylint: disable=bad-continuation
xblock_mixins=(), xblock_select=None, xblock_field_data_wrappers=(), disabled_xblock_types=lambda: [], # lint-amnesty, pylint: disable=bad-continuation, bad-option-value
# temporary parms to enable backward compatibility. remove once all envs migrated
db=None, collection=None, host=None, port=None, tz_aware=True, user=None, password=None,
db=None, collection=None, host=None, port=None, tz_aware=True, user=None, password=None, # lint-amnesty, pylint: disable=unused-argument
# allow lower level init args to pass harmlessly
** kwargs
):
'''
Set up the error-tracking logic.
'''
super(ModuleStoreReadBase, self).__init__(**kwargs)
super(ModuleStoreReadBase, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self._course_errors = defaultdict(make_error_tracker) # location -> ErrorLog
# TODO move the inheritance_cache_subsystem to classes which use it
self.metadata_inheritance_cache_subsystem = metadata_inheritance_cache_subsystem
@@ -1262,7 +1262,7 @@ class ModuleStoreReadBase(BulkOperationsMixin, ModuleStoreRead):
"""
if self.contentstore:
self.contentstore.close_connections()
super(ModuleStoreReadBase, self).close_connections()
super(ModuleStoreReadBase, self).close_connections() # lint-amnesty, pylint: disable=super-with-arguments
@contextmanager
def default_store(self, store_type):
@@ -1280,7 +1280,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite):
Implement interface functionality that can be shared.
'''
def __init__(self, contentstore, **kwargs):
super(ModuleStoreWriteBase, self).__init__(contentstore=contentstore, **kwargs)
super(ModuleStoreWriteBase, self).__init__(contentstore=contentstore, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.mixologist = Mixologist(self.xblock_mixins)
def partition_fields_by_scope(self, category, fields):
@@ -1300,7 +1300,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite):
result[field.scope][field_name] = value
return result
def create_course(self, org, course, run, user_id, fields=None, runtime=None, **kwargs):
def create_course(self, org, course, run, user_id, fields=None, runtime=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates any necessary other things for the course as a side effect and doesn't return
anything useful. The real subclass should call this before it returns the course.
@@ -1321,7 +1321,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite):
continue_version=True,
)
def clone_course(self, source_course_id, dest_course_id, user_id, fields=None, **kwargs):
def clone_course(self, source_course_id, dest_course_id, user_id, fields=None, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
This base method just copies the assets. The lower level impls must do the actual cloning of
content.
@@ -1340,7 +1340,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite):
# delete the assets
if self.contentstore:
self.contentstore.delete_all_course_assets(course_key)
super(ModuleStoreWriteBase, self).delete_course(course_key, user_id)
super(ModuleStoreWriteBase, self).delete_course(course_key, user_id) # lint-amnesty, pylint: disable=super-with-arguments
def _drop_database(self, database=True, collections=True, connections=True):
"""
@@ -1356,7 +1356,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite):
"""
if self.contentstore:
self.contentstore._drop_database(database, collections, connections) # pylint: disable=protected-access
super(ModuleStoreWriteBase, self)._drop_database(database, collections, connections)
super(ModuleStoreWriteBase, self)._drop_database(database, collections, connections) # lint-amnesty, pylint: disable=super-with-arguments
def create_child(self, user_id, parent_usage_key, block_type, block_id=None, fields=None, **kwargs):
"""
@@ -1374,7 +1374,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite):
fields (dict): A dictionary specifying initial values for some or all fields
in the newly created block
"""
item = self.create_item(user_id, parent_usage_key.course_key, block_type, block_id=block_id, fields=fields, **kwargs)
item = self.create_item(user_id, parent_usage_key.course_key, block_type, block_id=block_id, fields=fields, **kwargs) # lint-amnesty, pylint: disable=line-too-long
parent = self.get_item(parent_usage_key)
parent.children.append(item.location)
self.update_item(parent, user_id)

View File

@@ -10,7 +10,7 @@ import logging
import six
from pkg_resources import resource_filename
import re
import re # lint-amnesty, pylint: disable=wrong-import-order
from django.conf import settings
@@ -19,16 +19,16 @@ from django.conf import settings
if not settings.configured:
settings.configure()
from django.core.cache import caches, InvalidCacheBackendError
import django.dispatch
import django.utils
from django.utils.translation import get_language, to_locale
from edx_django_utils.cache import DEFAULT_REQUEST_CACHE
from django.core.cache import caches, InvalidCacheBackendError # lint-amnesty, pylint: disable=wrong-import-position
import django.dispatch # lint-amnesty, pylint: disable=wrong-import-position
import django.utils # lint-amnesty, pylint: disable=wrong-import-position
from django.utils.translation import get_language, to_locale # lint-amnesty, pylint: disable=wrong-import-position
from edx_django_utils.cache import DEFAULT_REQUEST_CACHE # lint-amnesty, pylint: disable=wrong-import-position
from xmodule.contentstore.django import contentstore
from xmodule.modulestore.draft_and_published import BranchSettingMixin
from xmodule.modulestore.mixed import MixedModuleStore
from xmodule.util.xmodule_django import get_current_request_hostname
from xmodule.contentstore.django import contentstore # lint-amnesty, pylint: disable=wrong-import-position
from xmodule.modulestore.draft_and_published import BranchSettingMixin # lint-amnesty, pylint: disable=wrong-import-position
from xmodule.modulestore.mixed import MixedModuleStore # lint-amnesty, pylint: disable=wrong-import-position
from xmodule.util.xmodule_django import get_current_request_hostname # lint-amnesty, pylint: disable=wrong-import-position
# We also may not always have the current request user (crum) module available
try:
@@ -68,7 +68,7 @@ class SwitchedSignal(django.dispatch.Signal):
All other args are passed to the constructor for django.dispatch.Signal.
"""
super(SwitchedSignal, self).__init__(*args, **kwargs)
super(SwitchedSignal, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.name = name
self._allow_signals = True
@@ -103,7 +103,7 @@ class SwitchedSignal(django.dispatch.Signal):
"ALLOW" if self._allow_signals else "BLOCK"
)
if self._allow_signals:
return super(SwitchedSignal, self).send(*args, **kwargs)
return super(SwitchedSignal, self).send(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
return []
def send_robust(self, *args, **kwargs):
@@ -121,7 +121,7 @@ class SwitchedSignal(django.dispatch.Signal):
"ALLOW" if self._allow_signals else "BLOCK"
)
if self._allow_signals:
return super(SwitchedSignal, self).send_robust(*args, **kwargs)
return super(SwitchedSignal, self).send_robust(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
return []
def __repr__(self):

View File

@@ -38,7 +38,7 @@ class BranchSettingMixin(object):
'branch_setting_func',
lambda: ModuleStoreEnum.Branch.published_only
)
super(BranchSettingMixin, self).__init__(*args, **kwargs)
super(BranchSettingMixin, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
# cache the branch setting on a local thread to support a multi-threaded environment
self.thread_cache = threading.local()
@@ -209,4 +209,4 @@ class UnsupportedRevisionError(ValueError):
ModuleStoreEnum.RevisionOption.published_only,
ModuleStoreEnum.RevisionOption.draft_only
]
super(UnsupportedRevisionError, self).__init__('revision not one of {}'.format(allowed_revisions))
super(UnsupportedRevisionError, self).__init__('revision not one of {}'.format(allowed_revisions)) # lint-amnesty, pylint: disable=super-with-arguments

View File

@@ -66,39 +66,39 @@ class EditInfoRuntimeMixin(six.with_metaclass(ABCMeta, object)):
"""
The datetime of the last change to this xblock content, children, or settings.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_edited_on(self, xblock):
"""
The datetime of the last change to this xblock content, children, or settings.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_subtree_edited_by(self, xblock):
"""
The user id of the last user to change content, children, or settings in this xblock's subtree
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_subtree_edited_on(self, xblock):
"""
The datetime of the last change content, children, or settings in this xblock's subtree
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_published_by(self, xblock):
"""
The user id of the last user to publish this specific xblock (or a previous version of it).
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@abstractmethod
def get_published_on(self, xblock):
"""
The datetime of the last time this specific xblock was published.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass

View File

@@ -15,14 +15,14 @@ class MultipleCourseBlocksFound(Exception):
"""
Raise this exception when Iterating over the course blocks return multiple course blocks.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class MultipleLibraryBlocksFound(Exception):
"""
Raise this exception when Iterating over the library blocks return multiple library blocks.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class InsufficientSpecificationError(Exception):
@@ -47,7 +47,7 @@ class ReferentialIntegrityError(Exception):
xblock points to a nonexistent child (which probably raises ItemNotFoundError instead depending
on context).
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class DuplicateItemError(Exception):
@@ -55,7 +55,7 @@ class DuplicateItemError(Exception):
Attempted to create an item which already exists.
"""
def __init__(self, element_id, store=None, collection=None):
super(DuplicateItemError, self).__init__()
super(DuplicateItemError, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.element_id = element_id
self.store = store
self.collection = collection
@@ -77,7 +77,7 @@ class VersionConflictError(Exception):
The caller asked for either draft or published head and gave a version which conflicted with it.
"""
def __init__(self, requestedLocation, currentHeadVersionGuid):
super(VersionConflictError, self).__init__(u'Requested {}, but current head is {}'.format(
super(VersionConflictError, self).__init__(u'Requested {}, but current head is {}'.format( # lint-amnesty, pylint: disable=super-with-arguments
requestedLocation,
currentHeadVersionGuid
))
@@ -91,7 +91,7 @@ class DuplicateCourseError(Exception):
"""
existing_entry will have the who, when, and other properties of the existing entry
"""
super(DuplicateCourseError, self).__init__(
super(DuplicateCourseError, self).__init__( # lint-amnesty, pylint: disable=super-with-arguments
u'Cannot create course {}, which duplicates {}'.format(course_id, existing_entry)
)
self.course_id = course_id
@@ -103,6 +103,6 @@ class InvalidBranchSetting(Exception):
Raised when the process' branch setting did not match the required setting for the attempted operation on a store.
"""
def __init__(self, expected_setting, actual_setting):
super(InvalidBranchSetting, self).__init__(u"Invalid branch: expected {} but got {}".format(expected_setting, actual_setting))
super(InvalidBranchSetting, self).__init__(u"Invalid branch: expected {} but got {}".format(expected_setting, actual_setting)) # lint-amnesty, pylint: disable=line-too-long, super-with-arguments
self.expected_setting = expected_setting
self.actual_setting = actual_setting

View File

@@ -20,10 +20,10 @@ _ = lambda text: text
class UserPartitionList(List):
"""Special List class for listing UserPartitions"""
def from_json(self, values):
def from_json(self, values): # lint-amnesty, pylint: disable=arguments-differ
return [UserPartition.from_json(v) for v in values]
def to_json(self, values):
def to_json(self, values): # lint-amnesty, pylint: disable=arguments-differ
return [user_partition.to_json()
for user_partition in values]
@@ -124,19 +124,19 @@ class InheritanceMixin(XBlockMixin):
)
static_asset_path = String(
display_name=_("Static Asset Path"),
help=_("Enter the path to use for files on the Files & Uploads page. This value overrides the Studio default, c4x://."),
help=_("Enter the path to use for files on the Files & Uploads page. This value overrides the Studio default, c4x://."), # lint-amnesty, pylint: disable=line-too-long
scope=Scope.settings,
default='',
)
use_latex_compiler = Boolean(
display_name=_("Enable LaTeX Compiler"),
help=_("Enter true or false. If true, you can use the LaTeX templates for HTML components and advanced Problem components."),
help=_("Enter true or false. If true, you can use the LaTeX templates for HTML components and advanced Problem components."), # lint-amnesty, pylint: disable=line-too-long
default=False,
scope=Scope.settings
)
max_attempts = Integer(
display_name=_("Maximum Attempts"),
help=_("Enter the maximum number of times a student can try to answer problems. By default, Maximum Attempts is set to null, meaning that students have an unlimited number of attempts for problems. You can override this course-wide setting for individual problems. However, if the course-wide setting is a specific number, you cannot set the Maximum Attempts for individual problems to unlimited."),
help=_("Enter the maximum number of times a student can try to answer problems. By default, Maximum Attempts is set to null, meaning that students have an unlimited number of attempts for problems. You can override this course-wide setting for individual problems. However, if the course-wide setting is a specific number, you cannot set the Maximum Attempts for individual problems to unlimited."), # lint-amnesty, pylint: disable=line-too-long
values={"min": 0}, scope=Scope.settings
)
matlab_api_key = String(
@@ -165,7 +165,7 @@ class InheritanceMixin(XBlockMixin):
video_auto_advance = Boolean(
display_name=_("Enable video auto-advance"),
help=_(
"Specify whether to show an auto-advance button in videos. If the student clicks it, when the last video in a unit finishes it will automatically move to the next unit and autoplay the first video."
"Specify whether to show an auto-advance button in videos. If the student clicks it, when the last video in a unit finishes it will automatically move to the next unit and autoplay the first video." # lint-amnesty, pylint: disable=line-too-long
),
scope=Scope.settings,
default=False
@@ -276,7 +276,7 @@ def compute_inherited_metadata(descriptor):
if descriptor.has_children:
parent_metadata = descriptor.xblock_kvs.inherited_settings.copy()
# add any of descriptor's explicitly set fields to the inheriting list
for field in InheritanceMixin.fields.values():
for field in InheritanceMixin.fields.values(): # lint-amnesty, pylint: disable=no-member
if field.is_set_on(descriptor):
# inherited_settings values are json repr
parent_metadata[field.name] = field.read_json(descriptor)
@@ -318,7 +318,7 @@ class InheritingFieldData(KvsFieldData):
parents.
"""
super(InheritingFieldData, self).__init__(**kwargs)
super(InheritingFieldData, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.inheritable_names = set(inheritable_names)
def has_default_value(self, name):
@@ -349,20 +349,20 @@ class InheritingFieldData(KvsFieldData):
if ancestor and \
ancestor.location.block_type == 'library_content' and \
self.has_default_value(name):
return super(InheritingFieldData, self).default(block, name)
return super(InheritingFieldData, self).default(block, name) # lint-amnesty, pylint: disable=super-with-arguments
while ancestor is not None:
if field.is_set_on(ancestor):
return field.read_json(ancestor)
else:
ancestor = ancestor.get_parent()
return super(InheritingFieldData, self).default(block, name)
return super(InheritingFieldData, self).default(block, name) # lint-amnesty, pylint: disable=super-with-arguments
def inheriting_field_data(kvs):
"""Create an InheritanceFieldData that inherits the names in InheritanceMixin."""
return InheritingFieldData(
inheritable_names=InheritanceMixin.fields.keys(),
inheritable_names=InheritanceMixin.fields.keys(), # lint-amnesty, pylint: disable=no-member
kvs=kvs,
)
@@ -375,7 +375,7 @@ class InheritanceKeyValueStore(KeyValueStore):
Note: inherited_settings is a dict of key to json values (internal xblock field repr)
"""
def __init__(self, initial_values=None, inherited_settings=None):
super(InheritanceKeyValueStore, self).__init__()
super(InheritanceKeyValueStore, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.inherited_settings = inherited_settings or {}
self._fields = initial_values or {}

View File

@@ -29,7 +29,7 @@ new_contract('AssetKey', AssetKey)
new_contract('AssetMetadata', AssetMetadata)
new_contract('LibraryLocator', LibraryLocator)
if six.PY2:
new_contract('long', long)
new_contract('long', long) # lint-amnesty, pylint: disable=undefined-variable
else:
new_contract('long', int)
@@ -154,7 +154,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
Initialize a MixedModuleStore. Here we look into our passed in kwargs which should be a
collection of other modulestore configuration information
"""
super(MixedModuleStore, self).__init__(contentstore, **kwargs)
super(MixedModuleStore, self).__init__(contentstore, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
if create_modulestore_instance is None:
raise ValueError('MixedModuleStore constructor must be passed a create_modulestore_instance function')
@@ -253,7 +253,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.has_item(usage_key, **kwargs)
@strip_key
def get_item(self, usage_key, depth=0, **kwargs):
def get_item(self, usage_key, depth=0, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
see parent doc
"""
@@ -261,7 +261,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.get_item(usage_key, depth, **kwargs)
@strip_key
def get_items(self, course_key, **kwargs):
def get_items(self, course_key, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns:
list of XModuleDescriptor instances for the matching items within the course with
@@ -404,7 +404,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.make_course_usage_key(course_key)
@strip_key
def get_course(self, course_key, depth=0, **kwargs):
def get_course(self, course_key, depth=0, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
returns the course module associated with the course_id. If no such course exists,
it returns None
@@ -452,7 +452,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
store = self._get_modulestore_for_courselike(course_id)
return store.has_course(course_id, ignore_case, **kwargs)
def delete_course(self, course_key, user_id):
def delete_course(self, course_key, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
See xmodule.modulestore.__init__.ModuleStoreWrite.delete_course
"""
@@ -593,7 +593,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.set_asset_metadata_attrs(asset_key, {attr: value}, user_id)
@contract(asset_key='AssetKey', attr_dict=dict, user_id='int|long')
def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id):
def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
Add/set the given dict of attrs on the asset at the given location. Value can be any type which pymongo accepts.
@@ -610,7 +610,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.set_asset_metadata_attrs(asset_key, attr_dict, user_id)
@strip_key
def get_parent_location(self, location, **kwargs):
def get_parent_location(self, location, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
returns the parent locations for a given location
"""
@@ -660,7 +660,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return errs
@strip_key
def create_course(self, org, course, run, user_id, **kwargs):
def create_course(self, org, course, run, user_id, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates and returns the course.
@@ -745,7 +745,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
dest_course_id.course, dest_course_id.run, fields, **kwargs)
# the super handles assets and any other necessities
super(MixedModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs)
super(MixedModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
else:
raise NotImplementedError("No code for cloning from {} to {}".format(
source_modulestore, dest_modulestore
@@ -791,7 +791,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
in the newly created block
"""
modulestore = self._verify_modulestore_support(parent_usage_key.course_key, 'create_child')
return modulestore.create_child(user_id, parent_usage_key, block_type, block_id=block_id, fields=fields, **kwargs)
return modulestore.create_child(user_id, parent_usage_key, block_type, block_id=block_id, fields=fields, **kwargs) # lint-amnesty, pylint: disable=line-too-long
@strip_key
@prepare_asides
@@ -805,7 +805,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.import_xblock(user_id, course_key, block_type, block_id, fields, runtime, **kwargs)
@strip_key
def copy_from_template(self, source_keys, dest_key, user_id, **kwargs):
def copy_from_template(self, source_keys, dest_key, user_id, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
See :py:meth `SplitMongoModuleStore.copy_from_template`
"""
@@ -814,7 +814,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
@strip_key
@prepare_asides
def update_item(self, xblock, user_id, allow_not_found=False, **kwargs):
def update_item(self, xblock, user_id, allow_not_found=False, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Update the xblock persisted to be the same as the given for all types of fields
(content, children, and metadata) attribute the change to the given user.
@@ -823,7 +823,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase):
return store.update_item(xblock, user_id, allow_not_found, **kwargs)
@strip_key
def delete_item(self, location, user_id, **kwargs):
def delete_item(self, location, user_id, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Delete the given item from persistence. kwargs allow modulestore specific parameters.
"""

View File

@@ -1,5 +1,5 @@
"""
This file contains helper functions for configuring module_store_setting settings and support for backward compatibility with older formats.
This file contains helper functions for configuring module_store_setting settings and support for backward compatibility with older formats. # lint-amnesty, pylint: disable=line-too-long
"""
@@ -112,10 +112,10 @@ def update_module_store_settings(
"""
for store in module_store_setting['default']['OPTIONS']['stores']:
if store['NAME'] == 'xml':
xml_store_options and store['OPTIONS'].update(xml_store_options)
xml_store_options and store['OPTIONS'].update(xml_store_options) # lint-amnesty, pylint: disable=expression-not-assigned
else:
module_store_options and store['OPTIONS'].update(module_store_options)
doc_store_settings and store['DOC_STORE_CONFIG'].update(doc_store_settings)
module_store_options and store['OPTIONS'].update(module_store_options) # lint-amnesty, pylint: disable=expression-not-assigned
doc_store_settings and store['DOC_STORE_CONFIG'].update(doc_store_settings) # lint-amnesty, pylint: disable=expression-not-assigned
if default_store:
mixed_stores = get_mixed_stores(module_store_setting)

View File

@@ -59,7 +59,7 @@ new_contract('CourseKey', CourseKey)
new_contract('AssetKey', AssetKey)
new_contract('AssetMetadata', AssetMetadata)
if six.PY2:
new_contract('long', long)
new_contract('long', long) # lint-amnesty, pylint: disable=undefined-variable
else:
new_contract('long', int)
new_contract('BlockUsageLocator', BlockUsageLocator)
@@ -95,7 +95,7 @@ class InvalidWriteError(Exception):
Raised to indicate that writing to a particular key
in the KeyValueStore is disabled
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
class MongoKeyValueStore(InheritanceKeyValueStore):
@@ -104,7 +104,7 @@ class MongoKeyValueStore(InheritanceKeyValueStore):
known to the MongoModuleStore (data, children, and metadata)
"""
def __init__(self, data, parent, children, metadata):
super(MongoKeyValueStore, self).__init__()
super(MongoKeyValueStore, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
if not isinstance(data, dict):
self._data = {'data': data}
else:
@@ -176,7 +176,7 @@ class MongoKeyValueStore(InheritanceKeyValueStore):
)
class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # lint-amnesty, pylint: disable=abstract-method
"""
A system that has a cache of module json that it will use to load modules
from, with a backup of calling to the underlying modulestore for more data
@@ -214,7 +214,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
id_manager = CourseLocationManager(course_key)
kwargs.setdefault('id_reader', id_manager)
kwargs.setdefault('id_generator', id_manager)
super(CachingDescriptorSystem, self).__init__(
super(CachingDescriptorSystem, self).__init__( # lint-amnesty, pylint: disable=super-with-arguments
field_data=None,
load_item=self.load_item,
**kwargs
@@ -228,7 +228,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
self.course_id = course_key
self.cached_metadata = cached_metadata
def load_item(self, location, for_parent=None):
def load_item(self, location, for_parent=None): # lint-amnesty, pylint: disable=method-hidden
"""
Return an XModule instance for the specified location
"""
@@ -344,7 +344,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
key = UsageKey.from_string(ref_string)
return key.replace(run=self.modulestore.fill_in_run(key.course_key).run)
def _convert_reference_fields_to_keys(self, class_, course_key, jsonfields):
def _convert_reference_fields_to_keys(self, class_, course_key, jsonfields): # lint-amnesty, pylint: disable=unused-argument
"""
Find all fields of type reference and convert the payload into UsageKeys
:param class_: the XBlock class
@@ -473,7 +473,7 @@ class MongoBulkOpsRecord(BulkOpsRecord):
Tracks whether there've been any writes per course and disables inheritance generation
"""
def __init__(self):
super(MongoBulkOpsRecord, self).__init__()
super(MongoBulkOpsRecord, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.dirty = False
@@ -502,11 +502,11 @@ class MongoBulkOpsMixin(BulkOperationsMixin):
bulk_ops_record.dirty = False # brand spanking clean now
return dirty
def _is_in_bulk_operation(self, course_id, ignore_case=False):
def _is_in_bulk_operation(self, course_id, ignore_case=False): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns whether a bulk operation is in progress for the given course.
"""
return super(MongoBulkOpsMixin, self)._is_in_bulk_operation(
return super(MongoBulkOpsMixin, self)._is_in_bulk_operation( # lint-amnesty, pylint: disable=super-with-arguments
course_id.for_branch(None), ignore_case
)
@@ -555,7 +555,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
:param doc_store_config: must have a host, db, and collection entries. Other common entries: port, tz_aware.
"""
super(MongoModuleStore, self).__init__(contentstore=contentstore, **kwargs)
super(MongoModuleStore, self).__init__(contentstore=contentstore, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def do_connection(
db, collection, host, port=27017, tz_aware=True, user=None, password=None, asset_collection=None, **kwargs
@@ -617,7 +617,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
If connections is True, then close the connection to the database as well.
"""
# drop the assets
super(MongoModuleStore, self)._drop_database(database, collections, connections)
super(MongoModuleStore, self)._drop_database(database, collections, connections) # lint-amnesty, pylint: disable=super-with-arguments
connection = self.collection.database.client
@@ -770,7 +770,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
course_id = self.fill_in_run(course_id)
if not force_refresh:
# see if we are first in the request cache (if present)
if self.request_cache is not None and six.text_type(course_id) in self.request_cache.data.get('metadata_inheritance', {}):
if self.request_cache is not None and six.text_type(course_id) in self.request_cache.data.get('metadata_inheritance', {}): # lint-amnesty, pylint: disable=line-too-long
return self.request_cache.data['metadata_inheritance'][six.text_type(course_id)]
# then look in any caching subsystem (e.g. memcached)
@@ -1102,7 +1102,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
"""
return BlockUsageLocator(course_key, 'course', course_key.run)
def get_course(self, course_key, depth=0, **kwargs):
def get_course(self, course_key, depth=0, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Get the course with the given courseid (org/course/run)
"""
@@ -1120,7 +1120,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
return None
@autoretry_read()
def has_course(self, course_key, ignore_case=False, **kwargs):
def has_course(self, course_key, ignore_case=False, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns the course_id of the course if it was found, else None
Note: we return the course_id instead of a boolean here since the found course may have
@@ -1164,7 +1164,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
except ItemNotFoundError:
return False
def get_item(self, usage_key, depth=0, using_descriptor_system=None, for_parent=None, **kwargs):
def get_item(self, usage_key, depth=0, using_descriptor_system=None, for_parent=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns an XModuleDescriptor instance for the item at location.
@@ -1214,7 +1214,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
])
@autoretry_read()
def get_items(
def get_items( # lint-amnesty, pylint: disable=arguments-differ
self,
course_id,
settings=None,
@@ -1286,7 +1286,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
)
return modules
def create_course(self, org, course, run, user_id, fields=None, **kwargs):
def create_course(self, org, course, run, user_id, fields=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates and returns the course.
@@ -1323,7 +1323,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
xblock = self.create_item(user_id, course_id, 'course', course_id.run, fields=fields, **kwargs)
# create any other necessary things as a side effect
super(MongoModuleStore, self).create_course(
super(MongoModuleStore, self).create_course( # lint-amnesty, pylint: disable=super-with-arguments
org, course, run, user_id, runtime=xblock.runtime, **kwargs
)
@@ -1397,7 +1397,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
xmodule.save()
return xmodule
def create_item(self, user_id, course_key, block_type, block_id=None, **kwargs):
def create_item(self, user_id, course_key, block_type, block_id=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates and saves a new item in a course.
@@ -1423,7 +1423,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
return xblock
def create_child(self, user_id, parent_usage_key, block_type, block_id=None, **kwargs):
def create_child(self, user_id, parent_usage_key, block_type, block_id=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates and saves a new xblock that as a child of the specified block
@@ -1453,7 +1453,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
else:
parent.children.insert(kwargs.get('position'), xblock.location)
self.update_item(parent, user_id, child_update=True)
self.update_item(parent, user_id, child_update=True) # lint-amnesty, pylint: disable=unexpected-keyword-arg
return xblock
@@ -1500,7 +1500,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
self._update_single_item(parent, update)
self._update_ancestors(parent, update)
def update_item(self, xblock, user_id, allow_not_found=False, force=False, isPublish=False,
def update_item(self, xblock, user_id, allow_not_found=False, force=False, isPublish=False, # lint-amnesty, pylint: disable=arguments-differ
is_publish_root=True):
"""
Update the persisted version of xblock to reflect its current values.
@@ -1565,10 +1565,10 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
self.refresh_cached_metadata_inheritance_tree(xblock.scope_ids.usage_id.course_key, xblock.runtime)
# fire signal that we've written to DB
except ItemNotFoundError:
if not allow_not_found:
if not allow_not_found: # lint-amnesty, pylint: disable=no-else-raise
raise
elif not self.has_course(course_key):
raise ItemNotFoundError(course_key)
raise ItemNotFoundError(course_key) # lint-amnesty, pylint: disable=raise-missing-from
return xblock
@@ -1637,7 +1637,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
but does NOT return a version agnostic location.
'''
assert location.branch is None
assert revision == ModuleStoreEnum.RevisionOption.published_only \
assert revision == ModuleStoreEnum.RevisionOption.published_only \ # lint-amnesty, pylint: disable=consider-using-in
or revision == ModuleStoreEnum.RevisionOption.draft_preferred
parent_cache = self._get_parent_cache(self.get_branch_setting())
@@ -1671,7 +1671,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
# no actual parent found
return cache_and_return(None)
if len(non_orphan_parents) > 1:
if len(non_orphan_parents) > 1: # lint-amnesty, pylint: disable=no-else-raise
# should never have multiple PUBLISHED parents
raise ReferentialIntegrityError(
u"{} parents claim {}".format(len(parents), location)
@@ -1723,7 +1723,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
return parent
return None
def get_modulestore_type(self, course_key=None):
def get_modulestore_type(self, course_key=None): # lint-amnesty, pylint: disable=arguments-differ, unused-argument
"""
Returns an enumeration-like type reflecting the type of this modulestore per ModuleStoreEnum.Type
Args:
@@ -1810,7 +1810,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
doc_id = None if course_assets is None else course_assets['_id']
if course_assets is None:
# Check to see if the course is created in the course collection.
if self.get_course(course_key) is None:
if self.get_course(course_key) is None: # lint-amnesty, pylint: disable=no-else-raise
raise ItemNotFoundError(course_key)
else:
# Course exists, so create matching assets document.
@@ -1910,7 +1910,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
self.asset_collection.insert_one(dest_assets)
@contract(asset_key='AssetKey', attr_dict=dict, user_id='int|long')
def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id):
def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
Add/set the given dict of attrs on the asset at the given location. Value can be any type which pymongo accepts.
@@ -1966,7 +1966,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
return 1
@contract(course_key='CourseKey', user_id='int|long')
def delete_all_asset_metadata(self, course_key, user_id):
def delete_all_asset_metadata(self, course_key, user_id): # lint-amnesty, pylint: disable=unused-argument
"""
Delete all of the assets which use this course_key as an identifier.
@@ -1991,7 +1991,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
self.database.client.admin.command('ismaster')
return {ModuleStoreEnum.Type.mongo: True}
except pymongo.errors.ConnectionFailure:
raise HeartbeatFailure("Can't connect to {}".format(self.database.name), 'mongo')
raise HeartbeatFailure("Can't connect to {}".format(self.database.name), 'mongo') # lint-amnesty, pylint: disable=raise-missing-from
def ensure_indexes(self):
"""
@@ -2028,7 +2028,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo
def convert_to_draft(self, location, user_id):
raise NotImplementedError()
def delete_item(self, location, user_id, **kwargs):
def delete_item(self, location, user_id, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
raise NotImplementedError()
def has_changes(self, xblock):

View File

@@ -60,7 +60,7 @@ class DraftModuleStore(MongoModuleStore):
This module also includes functionality to promote DRAFT modules (and their children)
to published modules.
"""
def get_item(self, usage_key, depth=0, revision=None, using_descriptor_system=None, **kwargs):
def get_item(self, usage_key, depth=0, revision=None, using_descriptor_system=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns an XModuleDescriptor instance for the item at usage_key.
@@ -94,13 +94,13 @@ class DraftModuleStore(MongoModuleStore):
is found at that usage_key
"""
def get_published():
return wrap_draft(super(DraftModuleStore, self).get_item(
return wrap_draft(super(DraftModuleStore, self).get_item( # lint-amnesty, pylint: disable=super-with-arguments
usage_key, depth=depth, using_descriptor_system=using_descriptor_system,
for_parent=kwargs.get('for_parent'),
))
def get_draft():
return wrap_draft(super(DraftModuleStore, self).get_item(
return wrap_draft(super(DraftModuleStore, self).get_item( # lint-amnesty, pylint: disable=super-with-arguments
as_draft(usage_key), depth=depth, using_descriptor_system=using_descriptor_system,
for_parent=kwargs.get('for_parent')
))
@@ -133,7 +133,7 @@ class DraftModuleStore(MongoModuleStore):
else:
raise UnsupportedRevisionError()
def has_item(self, usage_key, revision=None):
def has_item(self, usage_key, revision=None): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns True if location exists in this ModuleStore.
@@ -143,13 +143,13 @@ class DraftModuleStore(MongoModuleStore):
ModuleStoreEnum.RevisionOption.draft_only - checks for the draft item only
None - uses the branch setting, as follows:
if branch setting is ModuleStoreEnum.Branch.published_only, checks for the published item only
if branch setting is ModuleStoreEnum.Branch.draft_preferred, checks whether draft or published item exists
if branch setting is ModuleStoreEnum.Branch.draft_preferred, checks whether draft or published item exists # lint-amnesty, pylint: disable=line-too-long
"""
def has_published():
return super(DraftModuleStore, self).has_item(usage_key)
return super(DraftModuleStore, self).has_item(usage_key) # lint-amnesty, pylint: disable=super-with-arguments
def has_draft():
return super(DraftModuleStore, self).has_item(as_draft(usage_key))
return super(DraftModuleStore, self).has_item(as_draft(usage_key)) # lint-amnesty, pylint: disable=super-with-arguments
if revision == ModuleStoreEnum.RevisionOption.draft_only:
return has_draft()
@@ -165,7 +165,7 @@ class DraftModuleStore(MongoModuleStore):
else:
raise UnsupportedRevisionError()
def delete_course(self, course_key, user_id):
def delete_course(self, course_key, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
:param course_key: which course to delete
:param user_id: id of the user deleting the course
@@ -173,7 +173,7 @@ class DraftModuleStore(MongoModuleStore):
# Note: does not need to inform the bulk mechanism since after the course is deleted,
# it can't calculate inheritance anyway. Nothing is there to be dirty.
# delete the assets
super(DraftModuleStore, self).delete_course(course_key, user_id)
super(DraftModuleStore, self).delete_course(course_key, user_id) # lint-amnesty, pylint: disable=super-with-arguments
# delete all of the db records for the course
course_query = self._course_key_to_son(course_key)
@@ -206,7 +206,7 @@ class DraftModuleStore(MongoModuleStore):
)
# clone the assets
super(DraftModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields)
super(DraftModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields) # lint-amnesty, pylint: disable=super-with-arguments
# get the whole old course
new_course = self.get_course(dest_course_id)
@@ -242,7 +242,7 @@ class DraftModuleStore(MongoModuleStore):
log.info("Cloning module %s to %s....", original_loc, module.location)
if 'data' in module.fields and module.fields['data'].is_set_on(module) and isinstance(module.data, six.string_types):
if 'data' in module.fields and module.fields['data'].is_set_on(module) and isinstance(module.data, six.string_types): # lint-amnesty, pylint: disable=line-too-long
module.data = rewrite_nonportable_content_links(
original_loc.course_key, dest_course_id, module.data
)
@@ -282,7 +282,7 @@ class DraftModuleStore(MongoModuleStore):
# return only the parent(s) that satisfy the request
return [
BlockUsageLocator._from_deprecated_son(parent['_id'], location.course_key.run)
BlockUsageLocator._from_deprecated_son(parent['_id'], location.course_key.run) # lint-amnesty, pylint: disable=protected-access
for parent in parents
if (
# return all versions of the parent if revision is ModuleStoreEnum.RevisionOption.all
@@ -319,9 +319,9 @@ class DraftModuleStore(MongoModuleStore):
revision = ModuleStoreEnum.RevisionOption.published_only \
if self.get_branch_setting() == ModuleStoreEnum.Branch.published_only \
else ModuleStoreEnum.RevisionOption.draft_preferred
return super(DraftModuleStore, self).get_parent_location(location, revision, **kwargs)
return super(DraftModuleStore, self).get_parent_location(location, revision, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def create_xblock(self, runtime, course_key, block_type, block_id=None, fields=None, **kwargs):
def create_xblock(self, runtime, course_key, block_type, block_id=None, fields=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Create the new xmodule but don't save it. Returns the new module with a draft locator if
the category allows drafts. If the category does not allow drafts, just creates a published module.
@@ -332,13 +332,13 @@ class DraftModuleStore(MongoModuleStore):
:param runtime: if you already have an xmodule from the course, the xmodule.runtime value
:param fields: a dictionary of field names and values for the new xmodule
"""
new_block = super(DraftModuleStore, self).create_xblock(
new_block = super(DraftModuleStore, self).create_xblock( # lint-amnesty, pylint: disable=super-with-arguments
runtime, course_key, block_type, block_id, fields, **kwargs
)
new_block.location = self.for_branch_setting(new_block.location)
return wrap_draft(new_block)
def get_items(self, course_key, revision=None, **kwargs):
def get_items(self, course_key, revision=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Performance Note: This is generally a costly operation, but useful for wildcard searches.
@@ -360,7 +360,7 @@ class DraftModuleStore(MongoModuleStore):
returns either Draft or Published, preferring Draft items.
"""
def base_get_items(key_revision):
return super(DraftModuleStore, self).get_items(course_key, key_revision=key_revision, **kwargs)
return super(DraftModuleStore, self).get_items(course_key, key_revision=key_revision, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def draft_items():
return [wrap_draft(item) for item in base_get_items(MongoRevisionKey.draft)]
@@ -406,7 +406,7 @@ class DraftModuleStore(MongoModuleStore):
# get_item will wrap_draft so don't call it here (otherwise, it would override the is_draft attribute)
return self.get_item(location)
def _convert_to_draft(self, location, user_id, delete_published=False, ignore_if_draft=False):
def _convert_to_draft(self, location, user_id, delete_published=False, ignore_if_draft=False): # lint-amnesty, pylint: disable=unused-argument
"""
Internal method with additional internal parameters to convert a subtree to draft.
@@ -451,7 +451,7 @@ class DraftModuleStore(MongoModuleStore):
except pymongo.errors.DuplicateKeyError:
# prevent re-creation of DRAFT versions, unless explicitly requested to ignore
if not ignore_if_draft:
raise DuplicateItemError(item['_id'], self, 'collection')
raise DuplicateItemError(item['_id'], self, 'collection') # lint-amnesty, pylint: disable=raise-missing-from
# delete the old PUBLISHED version if requested
if delete_published:
@@ -463,8 +463,8 @@ class DraftModuleStore(MongoModuleStore):
# convert the subtree using the original item as the root
self._breadth_first(convert_item, [location])
def update_item(
self,
def update_item( # lint-amnesty, pylint: disable=arguments-differ
self, # lint-amnesty, pylint: disable=unused-argument
xblock,
user_id,
allow_not_found=False,
@@ -481,13 +481,13 @@ class DraftModuleStore(MongoModuleStore):
# if the revision is published, defer to base
if draft_loc.branch == MongoRevisionKey.published:
item = super(DraftModuleStore, self).update_item(xblock, user_id, allow_not_found)
item = super(DraftModuleStore, self).update_item(xblock, user_id, allow_not_found) # lint-amnesty, pylint: disable=super-with-arguments
course_key = xblock.location.course_key
if isPublish or (item.category in DIRECT_ONLY_CATEGORIES and not child_update):
self._flag_publish_event(course_key)
return item
if not super(DraftModuleStore, self).has_item(draft_loc):
if not super(DraftModuleStore, self).has_item(draft_loc): # lint-amnesty, pylint: disable=super-with-arguments
try:
# ignore any descendants which are already draft
self._convert_to_draft(xblock.location, user_id, ignore_if_draft=True)
@@ -499,10 +499,10 @@ class DraftModuleStore(MongoModuleStore):
raise
xblock.location = draft_loc
super(DraftModuleStore, self).update_item(xblock, user_id, allow_not_found, isPublish=isPublish)
super(DraftModuleStore, self).update_item(xblock, user_id, allow_not_found, isPublish=isPublish) # lint-amnesty, pylint: disable=super-with-arguments
return wrap_draft(xblock)
def delete_item(self, location, user_id, revision=None, **kwargs):
def delete_item(self, location, user_id, revision=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Delete an item from this modulestore.
The method determines which revisions to delete. It disconnects and deletes the subtree.
@@ -560,7 +560,7 @@ class DraftModuleStore(MongoModuleStore):
if self.collection.count_documents(query) > 1:
continue
parent_block = super(DraftModuleStore, self).get_item(parent_location)
parent_block = super(DraftModuleStore, self).get_item(parent_location) # lint-amnesty, pylint: disable=super-with-arguments
parent_block.children.remove(location)
parent_block.location = parent_location # ensure the location is with the correct revision
self.update_item(parent_block, user_id, child_update=True)
@@ -667,7 +667,7 @@ class DraftModuleStore(MongoModuleStore):
# use this store's request_cache
request_cache_getter=lambda args, kwargs: args[1],
)
def _cached_has_changes(self, request_cache, xblock):
def _cached_has_changes(self, request_cache, xblock): # lint-amnesty, pylint: disable=unused-argument
"""
Internal has_changes method that caches the result.
"""
@@ -684,7 +684,7 @@ class DraftModuleStore(MongoModuleStore):
else:
return False
def publish(self, location, user_id, **kwargs):
def publish(self, location, user_id, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Publish the subtree rooted at location to the live course and remove the drafts.
Such publishing may cause the deletion of previously published but subsequently deleted
@@ -727,7 +727,7 @@ class DraftModuleStore(MongoModuleStore):
# try to find the originally PUBLISHED version, if it exists
try:
original_published = super(DraftModuleStore, self).get_item(item_location)
original_published = super(DraftModuleStore, self).get_item(item_location) # lint-amnesty, pylint: disable=super-with-arguments
except ItemNotFoundError:
original_published = None
@@ -751,7 +751,7 @@ class DraftModuleStore(MongoModuleStore):
# update the published (not draft) item (ignoring that item is "draft"). The published
# may not exist; (if original_published is None); so, allow_not_found
super(DraftModuleStore, self).update_item(
super(DraftModuleStore, self).update_item( # lint-amnesty, pylint: disable=super-with-arguments
item, user_id, isPublish=True, is_publish_root=is_root, allow_not_found=True
)
to_be_deleted.append(as_draft(item_location).to_deprecated_son())
@@ -771,7 +771,7 @@ class DraftModuleStore(MongoModuleStore):
return self.get_item(as_published(location))
def unpublish(self, location, user_id, **kwargs):
def unpublish(self, location, user_id, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Turn the published version into a draft, removing the published version.
@@ -867,11 +867,11 @@ class DraftModuleStore(MongoModuleStore):
def _query_children_for_cache_children(self, course_key, items):
# first get non-draft in a round-trip
to_process_non_drafts = super(DraftModuleStore, self)._query_children_for_cache_children(course_key, items)
to_process_non_drafts = super(DraftModuleStore, self)._query_children_for_cache_children(course_key, items) # lint-amnesty, pylint: disable=super-with-arguments
to_process_dict = {}
for non_draft in to_process_non_drafts:
to_process_dict[BlockUsageLocator._from_deprecated_son(non_draft["_id"], course_key.run)] = non_draft
to_process_dict[BlockUsageLocator._from_deprecated_son(non_draft["_id"], course_key.run)] = non_draft # lint-amnesty, pylint: disable=protected-access
if self.get_branch_setting() == ModuleStoreEnum.Branch.draft_preferred:
# now query all draft content in another round-trip
@@ -888,7 +888,7 @@ class DraftModuleStore(MongoModuleStore):
# with the draft. This is because the semantics of the DraftStore is to
# always return the draft - if available
for draft in to_process_drafts:
draft_loc = BlockUsageLocator._from_deprecated_son(draft["_id"], course_key.run)
draft_loc = BlockUsageLocator._from_deprecated_son(draft["_id"], course_key.run) # lint-amnesty, pylint: disable=protected-access
draft_as_non_draft_loc = as_published(draft_loc)
# does non-draft exist in the collection

View File

@@ -17,9 +17,9 @@ class CourseKeyField(mongoengine.StringField):
"""
def __init__(self, **kwargs):
# it'd be useful to add init args such as support_deprecated, force_deprecated
super(CourseKeyField, self).__init__(**kwargs)
super(CourseKeyField, self).__init__(**kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def to_mongo(self, course_key):
def to_mongo(self, course_key): # lint-amnesty, pylint: disable=arguments-differ
"""
For now saves the course key in the deprecated form
"""
@@ -30,12 +30,12 @@ class CourseKeyField(mongoengine.StringField):
else:
return None
def to_python(self, course_key):
def to_python(self, course_key): # lint-amnesty, pylint: disable=arguments-differ
"""
Deserialize to a CourseKey instance
"""
# calling super b/c it decodes utf (and doesn't have circularity of from_python)
course_key = super(CourseKeyField, self).to_python(course_key)
course_key = super(CourseKeyField, self).to_python(course_key) # lint-amnesty, pylint: disable=super-with-arguments
assert isinstance(course_key, (type(None), six.string_types, CourseKey))
if course_key == '':
return None
@@ -47,9 +47,9 @@ class CourseKeyField(mongoengine.StringField):
def validate(self, value):
assert isinstance(value, (type(None), six.string_types, CourseKey))
if isinstance(value, CourseKey):
return super(CourseKeyField, self).validate(text_type(value))
return super(CourseKeyField, self).validate(text_type(value)) # lint-amnesty, pylint: disable=super-with-arguments
else:
return super(CourseKeyField, self).validate(value)
return super(CourseKeyField, self).validate(value) # lint-amnesty, pylint: disable=super-with-arguments
def prepare_query_value(self, _opt, value):
return self.to_mongo(value)
@@ -59,16 +59,16 @@ class UsageKeyField(mongoengine.StringField):
"""
Represent a UsageKey as a single string in Mongo
"""
def to_mongo(self, location):
def to_mongo(self, location): # lint-amnesty, pylint: disable=arguments-differ
"""
For now saves the usage key in the deprecated location i4x/c4x form
"""
assert isinstance(location, (type(None), UsageKey))
if location is None:
return None
return super(UsageKeyField, self).to_mongo(text_type(location))
return super(UsageKeyField, self).to_mongo(text_type(location)) # lint-amnesty, pylint: disable=super-with-arguments
def to_python(self, location):
def to_python(self, location): # lint-amnesty, pylint: disable=arguments-differ
"""
Deserialize to a UsageKey instance: for now it's a location missing the run
"""
@@ -76,7 +76,7 @@ class UsageKeyField(mongoengine.StringField):
if location == '':
return None
if isinstance(location, six.string_types):
location = super(UsageKeyField, self).to_python(location)
location = super(UsageKeyField, self).to_python(location) # lint-amnesty, pylint: disable=super-with-arguments
return Location.from_string(location)
else:
return location
@@ -84,9 +84,9 @@ class UsageKeyField(mongoengine.StringField):
def validate(self, value):
assert isinstance(value, (type(None), six.string_types, UsageKey))
if isinstance(value, UsageKey):
return super(UsageKeyField, self).validate(text_type(value))
return super(UsageKeyField, self).validate(text_type(value)) # lint-amnesty, pylint: disable=super-with-arguments
else:
return super(UsageKeyField, self).validate(value)
return super(UsageKeyField, self).validate(value) # lint-amnesty, pylint: disable=super-with-arguments
def prepare_query_value(self, _opt, value):
return self.to_mongo(value)

View File

@@ -95,7 +95,7 @@ class ImportExportReportGen(ReportGenerator):
Class which generates report for course import/export performance test data.
"""
def __init__(self, db_name):
super(ImportExportReportGen, self).__init__(db_name)
super(ImportExportReportGen, self).__init__(db_name) # lint-amnesty, pylint: disable=super-with-arguments
self._read_timing_data()
def _read_timing_data(self):
@@ -129,7 +129,7 @@ class ImportExportReportGen(ReportGenerator):
html = HTMLDocument("Results")
# Output comparison of each phase to a different table.
for phase in self.run_data.keys():
for phase in self.run_data.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary, too-many-nested-blocks
if phase in ('fake_assets',):
continue
per_phase = self.run_data[phase]
@@ -183,7 +183,7 @@ class FindReportGen(ReportGenerator):
Class which generates report for asset access performance test data.
"""
def __init__(self, db_name):
super(FindReportGen, self).__init__(db_name)
super(FindReportGen, self).__init__(db_name) # lint-amnesty, pylint: disable=super-with-arguments
self._read_timing_data()
def _read_timing_data(self):
@@ -229,7 +229,7 @@ class FindReportGen(ReportGenerator):
# per_phase = self.run_data[store]
# html.add_header(1, store)
for phase in self.run_data.keys():
for phase in self.run_data.keys(): # lint-amnesty, pylint: disable=consider-iterating-dictionary
per_phase = self.run_data[phase]
# Make the table header columns and the table.

View File

@@ -61,7 +61,7 @@ class CrossStoreXMLRoundtrip(unittest.TestCase):
perf_test = True
def setUp(self):
super(CrossStoreXMLRoundtrip, self).setUp()
super(CrossStoreXMLRoundtrip, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.export_dir = mkdtemp()
self.addCleanup(rmtree, self.export_dir, ignore_errors=True)
@@ -75,7 +75,7 @@ class CrossStoreXMLRoundtrip(unittest.TestCase):
"""
Generate timings for different amounts of asset metadata and different modulestores.
"""
if CodeBlockTimer is None:
if CodeBlockTimer is None: # lint-amnesty, pylint: disable=undefined-variable
pytest.skip("CodeBlockTimer undefined.")
desc = "XMLRoundTrip:{}->{}:{}".format(
@@ -84,9 +84,9 @@ class CrossStoreXMLRoundtrip(unittest.TestCase):
num_assets
)
with CodeBlockTimer(desc):
with CodeBlockTimer(desc): # lint-amnesty, pylint: disable=undefined-variable
with CodeBlockTimer("fake_assets"):
with CodeBlockTimer("fake_assets"): # lint-amnesty, pylint: disable=undefined-variable
# First, make the fake asset metadata.
make_asset_xml(num_assets, ASSET_XML_PATH)
validate_xml(ASSET_XSD_PATH, ASSET_XML_PATH)
@@ -96,7 +96,7 @@ class CrossStoreXMLRoundtrip(unittest.TestCase):
source_course_key = source_store.make_course_key('a', 'course', 'course')
dest_course_key = dest_store.make_course_key('a', 'course', 'course')
with CodeBlockTimer("initial_import"):
with CodeBlockTimer("initial_import"): # lint-amnesty, pylint: disable=undefined-variable
import_course_from_xml(
source_store,
'test_user',
@@ -108,7 +108,7 @@ class CrossStoreXMLRoundtrip(unittest.TestCase):
raise_on_failure=True,
)
with CodeBlockTimer("export"):
with CodeBlockTimer("export"): # lint-amnesty, pylint: disable=undefined-variable
export_course_to_xml(
source_store,
source_content,
@@ -117,7 +117,7 @@ class CrossStoreXMLRoundtrip(unittest.TestCase):
'exported_source_course',
)
with CodeBlockTimer("second_import"):
with CodeBlockTimer("second_import"): # lint-amnesty, pylint: disable=undefined-variable
import_course_from_xml(
dest_store,
'test_user',
@@ -194,7 +194,7 @@ class TestModulestoreAssetSize(unittest.TestCase):
results = asset_collection.map_reduce(mapper, reducer, "size_results")
result_str = "{} - Store: {:<15} - Num Assets: {:>6} - Result: {}\n".format(
self.test_run_time, SHORT_NAME_MAP[source_ms], num_assets, [r for r in results.find()]
self.test_run_time, SHORT_NAME_MAP[source_ms], num_assets, [r for r in results.find()] # lint-amnesty, pylint: disable=unnecessary-comprehension
)
with open("bson_sizes.txt", "a") as f:
f.write(result_str)

View File

@@ -112,7 +112,7 @@ def path_to_location(modulestore, usage_key, request=None, full_path=False):
position_list = []
for path_index in range(2, n - 1):
category = path[path_index].block_type
if category == 'sequential' or category == 'videosequence':
if category == 'sequential' or category == 'videosequence': # lint-amnesty, pylint: disable=consider-using-in
section_desc = modulestore.get_item(path[path_index])
# this calls get_children rather than just children b/c old mongo includes private children
# in children but not in get_children
@@ -151,7 +151,7 @@ def get_child_locations(section_desc, request, course_id):
"""
Return True if child is appendable based on request and request's user type.
"""
return (request and is_user_staff_and_not_masquerading_learner()) or not child_instance.visible_to_staff_only
return (request and is_user_staff_and_not_masquerading_learner()) or not child_instance.visible_to_staff_only # lint-amnesty, pylint: disable=consider-using-ternary
child_locs = []
for child in section_desc.get_children():

View File

@@ -27,7 +27,7 @@ class SplitMigrator(object):
name will be able to find the new elements.
"""
def __init__(self, split_modulestore, source_modulestore):
super(SplitMigrator, self).__init__()
super(SplitMigrator, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.split_modulestore = split_modulestore
self.source_modulestore = source_modulestore
@@ -50,7 +50,7 @@ class SplitMigrator(object):
# layer and kvs's know how to store it.
# locations are in location, children, conditionals, course.tab
# create the course: set fields to explicitly_set for each scope, id_root = new_course_locator, master_branch = 'production'
# create the course: set fields to explicitly_set for each scope, id_root = new_course_locator, master_branch = 'production' # lint-amnesty, pylint: disable=line-too-long
original_course = self.source_modulestore.get_course(source_course_key, **kwargs)
if original_course is None:
raise ItemNotFoundError(six.text_type(source_course_key))
@@ -94,7 +94,7 @@ class SplitMigrator(object):
"""
course_version_locator = new_course.id.version_agnostic()
# iterate over published course elements. Wildcarding rather than descending b/c some elements are orphaned (e.g.,
# iterate over published course elements. Wildcarding rather than descending b/c some elements are orphaned (e.g., # lint-amnesty, pylint: disable=line-too-long
# course about pages, conditionals)
for module in self.source_modulestore.get_items(
source_course_key, revision=ModuleStoreEnum.RevisionOption.published_only, **kwargs

View File

@@ -9,11 +9,11 @@ from contracts import check, contract
from opaque_keys.edx.locator import BlockUsageLocator
class BlockKey(namedtuple('BlockKey', 'type id')):
class BlockKey(namedtuple('BlockKey', 'type id')): # lint-amnesty, pylint: disable=missing-class-docstring
__slots__ = ()
@contract(type="string[>0]")
def __new__(cls, type, id):
def __new__(cls, type, id): # lint-amnesty, pylint: disable=redefined-builtin
return super(BlockKey, cls).__new__(cls, type, id)
@classmethod

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import logging
import sys
@@ -37,7 +37,7 @@ new_contract('CourseEnvelope', CourseEnvelope)
new_contract('XBlock', XBlock)
class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # lint-amnesty, pylint: disable=abstract-method
"""
A system that has a cache of a course version's json that it will use to load modules
from, with a backup of calling to the underlying modulestore for more data.
@@ -45,7 +45,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
Computes the settings (nee 'metadata') inheritance upon creation.
"""
@contract(course_entry=CourseEnvelope)
def __init__(self, modulestore, course_entry, default_class, module_data, lazy, **kwargs):
def __init__(self, modulestore, course_entry, default_class, module_data, lazy, **kwargs): # lint-amnesty, pylint: disable=redefined-outer-name
"""
Computes the settings inheritance and sets up the cache.
@@ -61,7 +61,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
"""
# needed by capa_problem (as runtime.filestore via this.resources_fs)
if course_entry.course_key.course:
root = modulestore.fs_root / course_entry.course_key.org / course_entry.course_key.course / course_entry.course_key.run
root = modulestore.fs_root / course_entry.course_key.org / course_entry.course_key.course / course_entry.course_key.run # lint-amnesty, pylint: disable=line-too-long
else:
root = modulestore.fs_root / str(course_entry.structure['_id'])
root.makedirs_p() # create directory if it doesn't exist
@@ -70,7 +70,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
kwargs.setdefault('id_reader', id_manager)
kwargs.setdefault('id_generator', id_manager)
super(CachingDescriptorSystem, self).__init__(
super(CachingDescriptorSystem, self).__init__( # lint-amnesty, pylint: disable=super-with-arguments
field_data=None,
load_item=self._load_item,
resources_fs=OSFS(root),
@@ -89,7 +89,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
@lazy
@contract(returns="dict(BlockKey: BlockKey)")
def _parent_map(self):
def _parent_map(self): # lint-amnesty, pylint: disable=missing-function-docstring
parent_map = {}
for block_key, block in six.iteritems(self.course_entry.structure['blocks']):
for child in block.fields.get('children', []):
@@ -114,7 +114,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
try:
return self.local_modules[usage_key]
except KeyError:
raise ItemNotFoundError
raise ItemNotFoundError # lint-amnesty, pylint: disable=raise-missing-from
else:
block_key = BlockKey.from_usage_key(usage_key)
version_guid = self.course_entry.course_key.version_guid
@@ -292,13 +292,13 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
"""
See :meth: cms.lib.xblock.runtime.EditInfoRuntimeMixin.get_edited_by
"""
return xblock._edited_by
return xblock._edited_by # lint-amnesty, pylint: disable=protected-access
def get_edited_on(self, xblock):
"""
See :class: cms.lib.xblock.runtime.EditInfoRuntimeMixin
"""
return xblock._edited_on
return xblock._edited_on # lint-amnesty, pylint: disable=protected-access
@contract(xblock='XBlock')
def get_subtree_edited_by(self, xblock):
@@ -382,7 +382,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin):
if aside.scope_ids.block_type == aside_type:
return aside
new_aside = super(CachingDescriptorSystem, self).get_aside_of_type(block, aside_type)
new_aside = super(CachingDescriptorSystem, self).get_aside_of_type(block, aside_type) # lint-amnesty, pylint: disable=super-with-arguments
new_aside._field_data = block._field_data # pylint: disable=protected-access
for key, _ in six.iteritems(new_aside.fields):

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import copy

View File

@@ -130,11 +130,11 @@ class QueryTimer(object):
tagger = Tagger(self._sample_rate)
metric_name = "{}.{}".format(self._metric_base, metric_name)
start = time()
start = time() # lint-amnesty, pylint: disable=unused-variable
try:
yield tagger
finally:
end = time()
end = time() # lint-amnesty, pylint: disable=unused-variable
tags = tagger.tags
tags.append('course:{}'.format(course_context))
@@ -244,7 +244,7 @@ class CourseStructureCache(object):
return pickle.loads(pickled_data)
else:
return pickle.loads(pickled_data, encoding='latin-1')
except Exception:
except Exception: # lint-amnesty, pylint: disable=broad-except
# The cached data is corrupt in some way, get rid of it.
log.warning("CourseStructureCache: Bad data in cache for %s", course_context)
self.cache.delete(key)
@@ -273,7 +273,7 @@ class MongoConnection(object):
"""
def __init__(
self, db, collection, host, port=27017, tz_aware=True, user=None, password=None,
asset_collection=None, retry_wait_time=0.1, **kwargs
asset_collection=None, retry_wait_time=0.1, **kwargs # lint-amnesty, pylint: disable=unused-argument
):
"""
Create & open the connection, authenticate, and provide pointers to the collections
@@ -301,7 +301,7 @@ class MongoConnection(object):
self.database.client.admin.command('ismaster')
return True
except pymongo.errors.ConnectionFailure:
raise HeartbeatFailure("Can't connect to {}".format(self.database.name), 'mongo')
raise HeartbeatFailure("Can't connect to {}".format(self.database.name), 'mongo') # lint-amnesty, pylint: disable=raise-missing-from
def get_structure(self, key, course_context=None):
"""

View File

@@ -140,9 +140,9 @@ new_contract('BlockKey', BlockKey)
new_contract('XBlock', XBlock)
class SplitBulkWriteRecord(BulkOpsRecord):
class SplitBulkWriteRecord(BulkOpsRecord): # lint-amnesty, pylint: disable=missing-class-docstring
def __init__(self):
super(SplitBulkWriteRecord, self).__init__()
super(SplitBulkWriteRecord, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self.initial_index = None
self.index = None
self.structures = {}
@@ -228,7 +228,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin):
]
# handle ignore case and general use
return super(SplitBulkWriteMixin, self)._get_bulk_ops_record(
return super(SplitBulkWriteMixin, self)._get_bulk_ops_record( # lint-amnesty, pylint: disable=super-with-arguments
course_key.replace(branch=None, version_guid=None), ignore_case
)
@@ -246,7 +246,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin):
course_key.replace(org=None, course=None, run=None, branch=None)
]
def _start_outermost_bulk_operation(self, bulk_write_record, course_key, ignore_case=False):
def _start_outermost_bulk_operation(self, bulk_write_record, course_key, ignore_case=False): # lint-amnesty, pylint: disable=arguments-differ
"""
Begin a bulk write operation on course_key.
"""
@@ -255,7 +255,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin):
bulk_write_record.index = copy.deepcopy(bulk_write_record.initial_index)
bulk_write_record.course_key = course_key
def _end_outermost_bulk_operation(self, bulk_write_record, structure_key):
def _end_outermost_bulk_operation(self, bulk_write_record, structure_key): # lint-amnesty, pylint: disable=arguments-differ
"""
End the active bulk write operation on structure_key (course or library key).
"""
@@ -317,7 +317,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin):
self.db_connection.delete_course_index(course_key)
def insert_course_index(self, course_key, index_entry):
def insert_course_index(self, course_key, index_entry): # lint-amnesty, pylint: disable=missing-function-docstring
bulk_write_record = self._get_bulk_ops_record(course_key)
if bulk_write_record.active:
bulk_write_record.index = index_entry
@@ -338,7 +338,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin):
else:
self.db_connection.update_course_index(updated_index_entry, course_context=course_key)
def get_structure(self, course_key, version_guid):
def get_structure(self, course_key, version_guid): # lint-amnesty, pylint: disable=missing-function-docstring
bulk_write_record = self._get_bulk_ops_record(course_key)
if bulk_write_record.active:
structure = bulk_write_record.structures.get(version_guid)
@@ -450,7 +450,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin):
ids.remove(definition_id)
definitions.append(definition)
if len(ids):
if len(ids): # lint-amnesty, pylint: disable=len-as-condition
# Query the db for the definitions.
defs_from_db = list(self.db_connection.get_definitions(list(ids), course_key))
defs_dict = {d.get('_id'): d for d in defs_from_db}
@@ -718,7 +718,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
:param doc_store_config: must have a host, db, and collection entries. Other common entries: port, tz_aware.
"""
super(SplitMongoModuleStore, self).__init__(contentstore, **kwargs)
super(SplitMongoModuleStore, self).__init__(contentstore, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
self.db_connection = MongoConnection(**doc_store_config)
@@ -765,7 +765,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
If connections is True, then close the connection to the database as well.
"""
# drop the assets
super(SplitMongoModuleStore, self)._drop_database(database, collections, connections)
super(SplitMongoModuleStore, self)._drop_database(database, collections, connections) # lint-amnesty, pylint: disable=super-with-arguments
self.db_connection._drop_database(database, collections, connections) # pylint: disable=protected-access
@@ -1014,7 +1014,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
)
@autoretry_read()
def get_courses(self, branch, **kwargs):
def get_courses(self, branch, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns a list of course descriptors matching any given qualifiers.
@@ -1188,9 +1188,9 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
return False
course_index = self.get_course_index(course_id, ignore_case)
return CourseLocator(course_index['org'], course_index['course'], course_index['run'], course_id.branch) if course_index else None
return CourseLocator(course_index['org'], course_index['course'], course_index['run'], course_id.branch) if course_index else None # lint-amnesty, pylint: disable=line-too-long
def has_library(self, library_id, ignore_case=False, **kwargs):
def has_library(self, library_id, ignore_case=False, **kwargs): # lint-amnesty, pylint: disable=unused-argument
"""
Does this library exist in this modulestore. This method does not verify that the branch &/or
version in the library_id exists.
@@ -1226,7 +1226,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
return self._get_block_from_structure(course_structure, BlockKey.from_usage_key(usage_key)) is not None
@contract(returns='XBlock')
def get_item(self, usage_key, depth=0, **kwargs):
def get_item(self, usage_key, depth=0, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
depth (int): An argument that some module stores may use to prefetch
descendants of the queried modules for more efficient results later
@@ -1242,13 +1242,13 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
with self.bulk_operations(usage_key.course_key):
course = self._lookup_course(usage_key.course_key)
items = self._load_items(course, [BlockKey.from_usage_key(usage_key)], depth, **kwargs)
if len(items) == 0:
if len(items) == 0: # lint-amnesty, pylint: disable=no-else-raise
raise ItemNotFoundError(usage_key)
elif len(items) > 1:
log.debug("Found more than one item for '{}'".format(usage_key))
return items[0]
def get_items(self, course_locator, settings=None, content=None, qualifiers=None, include_orphans=True, **kwargs):
def get_items(self, course_locator, settings=None, content=None, qualifiers=None, include_orphans=True, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns:
list of XModuleDescriptor instances for the matching items within the course with
@@ -1287,7 +1287,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
Check that the block matches all the criteria
"""
# do the checks which don't require loading any additional data
if ( # pylint: disable=bad-continuation
if ( # lint-amnesty, pylint: disable=bad-continuation, bad-option-value
self._block_matches(block_data, qualifiers) and
self._block_matches(block_data.fields, settings)
):
@@ -1337,7 +1337,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
for block_id, value in six.iteritems(course.structure['blocks']):
if _block_matches_all(value):
if not include_orphans:
if ( # pylint: disable=bad-continuation
if ( # lint-amnesty, pylint: disable=bad-continuation, bad-option-value
block_id.type in DETACHED_XBLOCK_TYPES or
self.has_path_to_root(block_id, course, path_cache, parents_cache)
):
@@ -1405,7 +1405,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
return has_path
def get_parent_location(self, locator, **kwargs):
def get_parent_location(self, locator, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Return the location (Locators w/ block_ids) for the parent of this location in this
course. Could use get_items(location, {'children': block_id}) but this is slightly faster.
@@ -1551,13 +1551,13 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
# and reconstruct the subtree from version_guid
next_entries = self.find_structures_derived_from([version_guid])
# must only scan cursor's once
next_versions = [struct for struct in next_entries]
next_versions = [struct for struct in next_entries] # lint-amnesty, pylint: disable=unnecessary-comprehension
result = {version_guid: [CourseLocator(version_guid=struct['_id']) for struct in next_versions]}
depth = 1
while depth < version_history_depth and len(next_versions) > 0:
depth += 1
next_entries = self.find_structures_derived_from([struct['_id'] for struct in next_versions])
next_versions = [struct for struct in next_entries]
next_versions = [struct for struct in next_entries] # lint-amnesty, pylint: disable=unnecessary-comprehension
for course_structure in next_versions:
result.setdefault(course_structure['previous_version'], []).append(
CourseLocator(version_guid=next_entries[-1]['_id']))
@@ -1620,7 +1620,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
Find the version_history_depth next versions of this definition. Return as a VersionTree
"""
# TODO implement
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def get_block_original_usage(self, usage_key):
"""
@@ -1726,7 +1726,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
serial += 1
@contract(returns='XBlock')
def create_item(self, user_id, course_key, block_type, block_id=None, definition_locator=None, fields=None,
def create_item(self, user_id, course_key, block_type, block_id=None, definition_locator=None, fields=None, # lint-amnesty, pylint: disable=arguments-differ
asides=None, force=False, **kwargs):
"""
Add a descriptor to persistence as an element
@@ -1764,7 +1764,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
specify version_guid or the one it specifies == the current head of the branch,
it progresses the course to point
to the new head and sets the active version to point to the new head
* If the locator has a org and course and run but its version_guid != current head, it raises VersionConflictError.
* If the locator has a org and course and run but its version_guid != current head, it raises VersionConflictError. # lint-amnesty, pylint: disable=line-too-long
NOTE: using a version_guid will end up creating a new version of the course. Your new item won't be in
the course id'd by version_guid but instead in one w/ a new version_guid. Ensure in this case that you get
@@ -1790,7 +1790,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
if definition_locator is None or isinstance(definition_locator.definition_id, LocalId):
definition_locator = self.create_definition_from_data(course_key, new_def_data, block_type, user_id)
elif new_def_data:
definition_locator, _ = self.update_definition_from_data(course_key, definition_locator, new_def_data, user_id)
definition_locator, _ = self.update_definition_from_data(course_key, definition_locator, new_def_data, user_id) # lint-amnesty, pylint: disable=line-too-long
# copy the structure and modify the new one
new_structure = self.version_structure(course_key, structure, user_id)
@@ -1843,7 +1843,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
# reconstruct the new_item from the cache
return self.get_item(item_loc)
def create_child(self, user_id, parent_usage_key, block_type, block_id=None, fields=None, asides=None, **kwargs):
def create_child(self, user_id, parent_usage_key, block_type, block_id=None, fields=None, asides=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates and saves a new xblock that as a child of the specified block
@@ -1923,13 +1923,13 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
**kwargs
)
# don't copy assets until we create the course in case something's awry
super(SplitMongoModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs)
super(SplitMongoModuleStore, self).clone_course(source_course_id, dest_course_id, user_id, fields, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
return new_course
DEFAULT_ROOT_COURSE_BLOCK_ID = 'course'
DEFAULT_ROOT_LIBRARY_BLOCK_ID = 'library'
def create_course(
def create_course( # lint-amnesty, pylint: disable=arguments-differ
self, org, course, run, user_id, master_branch=None, fields=None,
versions_dict=None, search_targets=None, root_category='course',
root_block_id=None, **kwargs
@@ -1985,7 +1985,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
search_targets, root_category, root_block_id, **kwargs
)
def _create_courselike(
def _create_courselike( # lint-amnesty, pylint: disable=too-many-statements
self, locator, user_id, master_branch, fields=None,
versions_dict=None, search_targets=None, root_category='course',
root_block_id=None, **kwargs
@@ -2007,7 +2007,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
# if building a wholly new structure
if versions_dict is None or master_branch not in versions_dict:
# create new definition and structure
definition_id = self.create_definition_from_data(locator, definition_fields, root_category, user_id).definition_id
definition_id = self.create_definition_from_data(locator, definition_fields, root_category, user_id).definition_id # lint-amnesty, pylint: disable=line-too-long
draft_structure = self._new_structure(
user_id,
@@ -2087,14 +2087,14 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
locator = LibraryLocator(org=org, library=library, branch=kwargs["master_branch"])
return self._create_courselike(locator, user_id, **kwargs)
def update_item(self, descriptor, user_id, allow_not_found=False, force=False, **kwargs):
def update_item(self, descriptor, user_id, allow_not_found=False, force=False, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Save the descriptor's fields. it doesn't descend the course dag to save the children.
Return the new descriptor (updated location).
raises ItemNotFoundError if the location does not exist.
Creates a new course version. If the descriptor's location has a org and course and run, it moves the course head
Creates a new course version. If the descriptor's location has a org and course and run, it moves the course head # lint-amnesty, pylint: disable=line-too-long
pointer. If the version_guid of the descriptor points to a non-head version and there's been an intervening
change to this item, it raises a VersionConflictError unless force is True. In the force case, it forks
the course but leaves the head pointer where it is (this change will not be in the course head).
@@ -2153,7 +2153,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
# check children
if partitioned_fields.get(Scope.children, {}): # purposely not 'is not None'
serialized_children = [BlockKey.from_usage_key(child) for child in partitioned_fields[Scope.children]['children']]
serialized_children = [BlockKey.from_usage_key(child) for child in partitioned_fields[Scope.children]['children']] # lint-amnesty, pylint: disable=line-too-long
is_updated = is_updated or original_entry.fields.get('children', []) != serialized_children
if is_updated:
settings['children'] = serialized_children
@@ -2249,7 +2249,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
else:
inherited_settings = parent_xblock.xblock_kvs.inherited_settings.copy()
if fields is not None:
for field_name in inheritance.InheritanceMixin.fields:
for field_name in inheritance.InheritanceMixin.fields: # lint-amnesty, pylint: disable=not-an-iterable
if field_name in fields:
inherited_settings[field_name] = fields[field_name]
@@ -2307,7 +2307,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
else:
return xblock
def _persist_subdag(self, course_key, xblock, user_id, structure_blocks, new_id):
def _persist_subdag(self, course_key, xblock, user_id, structure_blocks, new_id): # lint-amnesty, pylint: disable=missing-function-docstring
# persist the definition if persisted != passed
partitioned_fields = self.partition_xblock_fields_by_scope(xblock)
new_def_data = self._serialize_fields(xblock.category, partitioned_fields[Scope.content])
@@ -2342,7 +2342,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
for child in xblock.children:
if isinstance(child.block_id, LocalId):
child_block = xblock.system.get_block(child)
is_updated = self._persist_subdag(course_key, child_block, user_id, structure_blocks, new_id) or is_updated
is_updated = self._persist_subdag(course_key, child_block, user_id, structure_blocks, new_id) or is_updated # lint-amnesty, pylint: disable=line-too-long
children.append(BlockKey.from_usage_key(child_block.location))
else:
children.append(BlockKey.from_usage_key(child))
@@ -2471,7 +2471,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
BlockKey.from_usage_key(subtree_root)
)
)
if len(parents) and not parent_found:
if len(parents) and not parent_found: # lint-amnesty, pylint: disable=len-as-condition
raise ItemNotFoundError(parents)
# update/create the subtree and its children in destination (skipping blacklist)
orphans.update(
@@ -2660,7 +2660,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
return new_blocks
def delete_item(self, usage_locator, user_id, force=False):
def delete_item(self, usage_locator, user_id, force=False): # lint-amnesty, pylint: disable=arguments-differ
"""
Delete the block or tree rooted at block (if delete_children) and any references w/in the course to the block
from a new version of the course structure.
@@ -2670,7 +2670,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
raises ItemNotFoundError if the location does not exist.
raises ValueError if usage_locator points to the structure root
Creates a new course version. If the descriptor's location has a org, a course, and a run, it moves the course head
Creates a new course version. If the descriptor's location has a org, a course, and a run, it moves the course head # lint-amnesty, pylint: disable=line-too-long
pointer. If the version_guid of the descriptor points to a non-head version and there's been an intervening
change to this item, it raises a VersionConflictError unless force is True. In the force case, it forks
the course but leaves the head pointer where it is (this change will not be in the course head).
@@ -2755,7 +2755,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
for block_key in to_delete:
del blocks[block_key]
def delete_course(self, course_key, user_id):
def delete_course(self, course_key, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
Remove the given course from the course index.
@@ -2798,14 +2798,14 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
# update the inheriting w/ what should pass to children
inheriting_settings = inherited_settings_map[block_key].copy()
block_fields = block_data.fields
for field_name in inheritance.InheritanceMixin.fields:
for field_name in inheritance.InheritanceMixin.fields: # lint-amnesty, pylint: disable=not-an-iterable
if field_name in block_fields:
inheriting_settings[field_name] = block_fields[field_name]
for child in block_fields.get('children', []):
try:
if child in inherited_from:
raise Exception(u'Infinite loop detected when inheriting to {}, having already inherited from {}'.format(child, inherited_from))
raise Exception(u'Infinite loop detected when inheriting to {}, having already inherited from {}'.format(child, inherited_from)) # lint-amnesty, pylint: disable=line-too-long
self.inherit_settings(
block_map,
BlockKey(*child),
@@ -2839,7 +2839,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
return descendent_map
def get_modulestore_type(self, course_key=None):
def get_modulestore_type(self, course_key=None): # lint-amnesty, pylint: disable=arguments-differ, unused-argument
"""
Returns an enumeration-like type reflecting the type of this modulestore, per ModuleStoreEnum.Type.
@@ -2854,7 +2854,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
"""
try:
course_assets = self._lookup_course(course_key).structure.get('assets', {})
except (InsufficientSpecificationError, VersionConflictError) as err:
except (InsufficientSpecificationError, VersionConflictError) as err: # lint-amnesty, pylint: disable=unused-variable
log.warning(u'Error finding assets for org "%s" course "%s" on asset '
u'request. Either version of course_key is None or invalid.',
course_key.org, course_key.course)
@@ -2929,7 +2929,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
return self.save_asset_metadata_list([asset_metadata, ], user_id, import_only)
@contract(asset_key='AssetKey', attr_dict=dict)
def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id):
def set_asset_metadata_attrs(self, asset_key, attr_dict, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
Add/set the given dict of attrs on the asset at the given location. Value can be any type which pymongo accepts.
@@ -3032,7 +3032,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
# update the index entry if appropriate
self._update_head(course_locator, index_entry, course_locator.branch, new_structure['_id'])
def convert_references_to_keys(self, course_key, xblock_class, jsonfields, blocks):
def convert_references_to_keys(self, course_key, xblock_class, jsonfields, blocks): # lint-amnesty, pylint: disable=unused-argument
"""
Convert the given serialized fields to the deserialized values by finding all references
and converting them.
@@ -3106,7 +3106,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
index_entry['versions'][course_key.branch]
)
def _find_local_root(self, element_to_find, possibility, tree):
def _find_local_root(self, element_to_find, possibility, tree): # lint-amnesty, pylint: disable=missing-function-docstring
if possibility not in tree:
return False
if element_to_find in tree[possibility]:
@@ -3400,7 +3400,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase):
tmp_new_asides_data[aside_type] = asd
result_list = []
for i, aside in enumerate(block.asides):
for i, aside in enumerate(block.asides): # lint-amnesty, pylint: disable=unused-variable
if aside['aside_type'] in tmp_new_asides_data:
result_list.append(tmp_new_asides_data.pop(aside['aside_type']))
updated = True

View File

@@ -23,7 +23,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
A subclass of Split that supports a dual-branch fall-back versioning framework
with a Draft branch that falls back to a Published branch.
"""
def create_course(self, org, course, run, user_id, skip_auto_publish=False, **kwargs):
def create_course(self, org, course, run, user_id, skip_auto_publish=False, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Creates and returns the course.
@@ -38,7 +38,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
"""
master_branch = kwargs.pop('master_branch', ModuleStoreEnum.BranchName.draft)
with self.bulk_operations(CourseLocator(org, course, run), ignore_case=True):
item = super(DraftVersioningModuleStore, self).create_course(
item = super(DraftVersioningModuleStore, self).create_course( # lint-amnesty, pylint: disable=super-with-arguments
org, course, run, user_id, master_branch=master_branch, **kwargs
)
if master_branch == ModuleStoreEnum.BranchName.draft and not skip_auto_publish:
@@ -51,7 +51,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
# in this; so, this manually calls the grandparent and above methods.
with self.branch_setting(ModuleStoreEnum.Branch.draft_preferred, item.id):
# NOTE: DO NOT CHANGE THE SUPER. See comment above
super(SplitMongoModuleStore, self).create_course(
super(SplitMongoModuleStore, self).create_course( # lint-amnesty, pylint: disable=bad-super-call
org, course, run, user_id, runtime=item.runtime, **kwargs
)
@@ -59,7 +59,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
def get_course(self, course_id, depth=0, **kwargs):
course_id = self._map_revision_to_branch(course_id)
return super(DraftVersioningModuleStore, self).get_course(course_id, depth=depth, **kwargs)
return super(DraftVersioningModuleStore, self).get_course(course_id, depth=depth, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def get_library(self, library_id, depth=0, head_validation=True, **kwargs):
if not head_validation and library_id.version_guid:
@@ -67,42 +67,42 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
self, library_id, depth=depth, head_validation=head_validation, **kwargs
)
library_id = self._map_revision_to_branch(library_id)
return super(DraftVersioningModuleStore, self).get_library(library_id, depth=depth, **kwargs)
return super(DraftVersioningModuleStore, self).get_library(library_id, depth=depth, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def clone_course(self, source_course_id, dest_course_id, user_id, fields=None, revision=None, **kwargs):
def clone_course(self, source_course_id, dest_course_id, user_id, fields=None, revision=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
See :py:meth: xmodule.modulestore.split_mongo.split.SplitMongoModuleStore.clone_course
"""
dest_course_id = self._map_revision_to_branch(dest_course_id, revision=revision)
return super(DraftVersioningModuleStore, self).clone_course(
return super(DraftVersioningModuleStore, self).clone_course( # lint-amnesty, pylint: disable=super-with-arguments
source_course_id, dest_course_id, user_id, fields=fields, **kwargs
)
def get_course_summaries(self, **kwargs):
def get_course_summaries(self, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns course summaries on the Draft or Published branch depending on the branch setting.
"""
branch_setting = self.get_branch_setting()
if branch_setting == ModuleStoreEnum.Branch.draft_preferred:
return super(DraftVersioningModuleStore, self).get_course_summaries(
return super(DraftVersioningModuleStore, self).get_course_summaries( # lint-amnesty, pylint: disable=super-with-arguments
ModuleStoreEnum.BranchName.draft, **kwargs
)
elif branch_setting == ModuleStoreEnum.Branch.published_only:
return super(DraftVersioningModuleStore, self).get_course_summaries(
return super(DraftVersioningModuleStore, self).get_course_summaries( # lint-amnesty, pylint: disable=super-with-arguments
ModuleStoreEnum.BranchName.published, **kwargs
)
else:
raise InsufficientSpecificationError()
def get_courses(self, **kwargs):
def get_courses(self, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns all the courses on the Draft or Published branch depending on the branch setting.
"""
branch_setting = self.get_branch_setting()
if branch_setting == ModuleStoreEnum.Branch.draft_preferred:
return super(DraftVersioningModuleStore, self).get_courses(ModuleStoreEnum.BranchName.draft, **kwargs)
return super(DraftVersioningModuleStore, self).get_courses(ModuleStoreEnum.BranchName.draft, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
elif branch_setting == ModuleStoreEnum.Branch.published_only:
return super(DraftVersioningModuleStore, self).get_courses(ModuleStoreEnum.BranchName.published, **kwargs)
return super(DraftVersioningModuleStore, self).get_courses(ModuleStoreEnum.BranchName.published, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
else:
raise InsufficientSpecificationError()
@@ -117,14 +117,14 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
# version_agnostic b/c of above assumption in docstring
self.publish(location.version_agnostic(), user_id, blacklist=EXCLUDE_ALL, **kwargs)
def copy_from_template(self, source_keys, dest_key, user_id, **kwargs):
def copy_from_template(self, source_keys, dest_key, user_id, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
See :py:meth `SplitMongoModuleStore.copy_from_template`
"""
source_keys = [self._map_revision_to_branch(key) for key in source_keys]
dest_key = self._map_revision_to_branch(dest_key)
head_validation = kwargs.get('head_validation')
new_keys = super(DraftVersioningModuleStore, self).copy_from_template(
new_keys = super(DraftVersioningModuleStore, self).copy_from_template( # lint-amnesty, pylint: disable=super-with-arguments
source_keys, dest_key, user_id, head_validation
)
if dest_key.branch == ModuleStoreEnum.BranchName.draft:
@@ -141,14 +141,14 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
keys_to_check.extend(children)
return new_keys
def update_item(self, descriptor, user_id, allow_not_found=False, force=False, asides=None, **kwargs):
def update_item(self, descriptor, user_id, allow_not_found=False, force=False, asides=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
old_descriptor_locn = descriptor.location
descriptor.location = self._map_revision_to_branch(old_descriptor_locn)
emit_signals = descriptor.location.branch == ModuleStoreEnum.BranchName.published \
or descriptor.location.block_type in DIRECT_ONLY_CATEGORIES
with self.bulk_operations(descriptor.location.course_key, emit_signals=emit_signals):
item = super(DraftVersioningModuleStore, self).update_item(
item = super(DraftVersioningModuleStore, self).update_item( # lint-amnesty, pylint: disable=super-with-arguments
descriptor,
user_id,
allow_not_found=allow_not_found,
@@ -169,7 +169,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
emit_signals = course_key.branch == ModuleStoreEnum.BranchName.published \
or block_type in DIRECT_ONLY_CATEGORIES
with self.bulk_operations(course_key, emit_signals=emit_signals):
item = super(DraftVersioningModuleStore, self).create_item(
item = super(DraftVersioningModuleStore, self).create_item( # lint-amnesty, pylint: disable=super-with-arguments
user_id, course_key, block_type, block_id=block_id,
definition_locator=definition_locator, fields=fields, asides=asides,
force=force, **kwargs
@@ -184,7 +184,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
):
parent_usage_key = self._map_revision_to_branch(parent_usage_key)
with self.bulk_operations(parent_usage_key.course_key):
item = super(DraftVersioningModuleStore, self).create_child(
item = super(DraftVersioningModuleStore, self).create_child( # lint-amnesty, pylint: disable=super-with-arguments
user_id, parent_usage_key, block_type, block_id=block_id,
fields=fields, asides=asides, **kwargs
)
@@ -193,7 +193,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
self._auto_publish_no_children(parent_usage_key, item.location.block_type, user_id, **kwargs)
return item
def delete_item(self, location, user_id, revision=None, skip_auto_publish=False, **kwargs):
def delete_item(self, location, user_id, revision=None, skip_auto_publish=False, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Delete the given item from persistence. kwargs allow modulestore specific parameters.
@@ -218,7 +218,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
autopublish_parent = False
with self.bulk_operations(location.course_key):
if isinstance(location, LibraryUsageLocator):
branches_to_delete = [ModuleStoreEnum.BranchName.library] # Libraries don't yet have draft/publish support
branches_to_delete = [ModuleStoreEnum.BranchName.library] # Libraries don't yet have draft/publish support # lint-amnesty, pylint: disable=line-too-long
elif location.block_type in DIRECT_ONLY_CATEGORIES:
branches_to_delete = [ModuleStoreEnum.BranchName.published, ModuleStoreEnum.BranchName.draft]
elif revision == ModuleStoreEnum.RevisionOption.all:
@@ -238,7 +238,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
self._flag_publish_event(location.course_key)
for branch in branches_to_delete:
branched_location = location.for_branch(branch)
super(DraftVersioningModuleStore, self).delete_item(branched_location, user_id)
super(DraftVersioningModuleStore, self).delete_item(branched_location, user_id) # lint-amnesty, pylint: disable=super-with-arguments
if autopublish_parent:
self.publish(parent_loc.version_agnostic(), user_id, blacklist=EXCLUDE_ALL, **kwargs)
@@ -269,29 +269,29 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
else:
raise UnsupportedRevisionError()
def has_item(self, usage_key, revision=None):
def has_item(self, usage_key, revision=None): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns True if location exists in this ModuleStore.
"""
usage_key = self._map_revision_to_branch(usage_key, revision=revision)
return super(DraftVersioningModuleStore, self).has_item(usage_key)
return super(DraftVersioningModuleStore, self).has_item(usage_key) # lint-amnesty, pylint: disable=super-with-arguments
def get_item(self, usage_key, depth=0, revision=None, **kwargs):
def get_item(self, usage_key, depth=0, revision=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns the item identified by usage_key and revision.
"""
usage_key = self._map_revision_to_branch(usage_key, revision=revision)
return super(DraftVersioningModuleStore, self).get_item(usage_key, depth=depth, **kwargs)
return super(DraftVersioningModuleStore, self).get_item(usage_key, depth=depth, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def get_items(self, course_locator, revision=None, **kwargs):
def get_items(self, course_locator, revision=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Returns a list of XModuleDescriptor instances for the matching items within the course with
the given course_locator.
"""
course_locator = self._map_revision_to_branch(course_locator, revision=revision)
return super(DraftVersioningModuleStore, self).get_items(course_locator, **kwargs)
return super(DraftVersioningModuleStore, self).get_items(course_locator, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def get_parent_location(self, location, revision=None, **kwargs):
def get_parent_location(self, location, revision=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
'''
Returns the given location's parent location in this course.
Args:
@@ -306,7 +306,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
if revision == ModuleStoreEnum.RevisionOption.draft_preferred:
revision = ModuleStoreEnum.RevisionOption.draft_only
location = self._map_revision_to_branch(location, revision=revision)
return super(DraftVersioningModuleStore, self).get_parent_location(location, **kwargs)
return super(DraftVersioningModuleStore, self).get_parent_location(location, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def get_block_original_usage(self, usage_key):
"""
@@ -315,18 +315,18 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
copy was inherited.
"""
usage_key = self._map_revision_to_branch(usage_key)
return super(DraftVersioningModuleStore, self).get_block_original_usage(usage_key)
return super(DraftVersioningModuleStore, self).get_block_original_usage(usage_key) # lint-amnesty, pylint: disable=super-with-arguments
def get_orphans(self, course_key, **kwargs):
course_key = self._map_revision_to_branch(course_key)
return super(DraftVersioningModuleStore, self).get_orphans(course_key, **kwargs)
return super(DraftVersioningModuleStore, self).get_orphans(course_key, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments
def fix_not_found(self, course_key, user_id):
def fix_not_found(self, course_key, user_id): # lint-amnesty, pylint: disable=arguments-differ
"""
Fix any children which point to non-existent blocks in the course's published and draft branches
"""
for branch in [ModuleStoreEnum.RevisionOption.published_only, ModuleStoreEnum.RevisionOption.draft_only]:
super(DraftVersioningModuleStore, self).fix_not_found(
super(DraftVersioningModuleStore, self).fix_not_found( # lint-amnesty, pylint: disable=super-with-arguments
self._map_revision_to_branch(course_key, branch),
user_id
)
@@ -368,12 +368,12 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
return has_changes_subtree(BlockKey.from_usage_key(xblock.location))
def publish(self, location, user_id, blacklist=None, **kwargs):
def publish(self, location, user_id, blacklist=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Publishes the subtree under location from the draft branch to the published branch
Returns the newly published item.
"""
super(DraftVersioningModuleStore, self).copy(
super(DraftVersioningModuleStore, self).copy( # lint-amnesty, pylint: disable=super-with-arguments
user_id,
# Directly using the replace function rather than the for_branch function
# because for_branch obliterates the version_guid and will lead to missed version conflicts.
@@ -492,7 +492,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
old_parent_location = original_parent_location.course_key.make_usage_key(block_key.type, block_key.id)
self.update_item_parent(item_location, original_parent_location, old_parent_location, user_id)
def force_publish_course(self, course_locator, user_id, commit=False):
def force_publish_course(self, course_locator, user_id, commit=False): # lint-amnesty, pylint: disable=unused-argument
"""
Helper method to forcefully publish a course,
making the published branch point to the same structure as the draft branch.
@@ -514,19 +514,19 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
return self.get_course_index(course_locator)['versions']
return versions
def get_course_history_info(self, course_locator):
def get_course_history_info(self, course_locator): # lint-amnesty, pylint: disable=arguments-differ
"""
See :py:meth `xmodule.modulestore.split_mongo.split.SplitMongoModuleStore.get_course_history_info`
"""
course_locator = self._map_revision_to_branch(course_locator)
return super(DraftVersioningModuleStore, self).get_course_history_info(course_locator)
return super(DraftVersioningModuleStore, self).get_course_history_info(course_locator) # lint-amnesty, pylint: disable=super-with-arguments
def get_course_successors(self, course_locator, version_history_depth=1):
"""
See :py:meth `xmodule.modulestore.split_mongo.split.SplitMongoModuleStore.get_course_successors`
"""
course_locator = self._map_revision_to_branch(course_locator)
return super(DraftVersioningModuleStore, self).get_course_successors(
return super(DraftVersioningModuleStore, self).get_course_successors( # lint-amnesty, pylint: disable=super-with-arguments
course_locator, version_history_depth=version_history_depth
)
@@ -535,7 +535,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
See :py:meth `xmodule.modulestore.split_mongo.split.SplitMongoModuleStore.get_block_generations`
"""
block_locator = self._map_revision_to_branch(block_locator)
return super(DraftVersioningModuleStore, self).get_block_generations(block_locator)
return super(DraftVersioningModuleStore, self).get_block_generations(block_locator) # lint-amnesty, pylint: disable=super-with-arguments
def has_published_version(self, xblock):
"""
@@ -550,7 +550,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
:param source: the location of the source (its revision must be None)
"""
# This is a no-op in Split since a draft version of the data always remains
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
def _get_head(self, xblock, branch):
""" Gets block at the head of specified branch """
@@ -592,7 +592,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
# Importing the block and publishing the block links the draft & published blocks' version history.
draft_block = self.import_xblock(user_id, draft_course, block_type, block_id, fields,
runtime, **kwargs)
return self.publish(draft_block.location.version_agnostic(), user_id, blacklist=EXCLUDE_ALL, **kwargs)
return self.publish(draft_block.location.version_agnostic(), user_id, blacklist=EXCLUDE_ALL, **kwargs) # lint-amnesty, pylint: disable=line-too-long
# do the import
partitioned_fields = self.partition_fields_by_scope(block_type, fields)
@@ -614,12 +614,12 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
@contract(asset_key='AssetKey')
def find_asset_metadata(self, asset_key, **kwargs):
return super(DraftVersioningModuleStore, self).find_asset_metadata(
return super(DraftVersioningModuleStore, self).find_asset_metadata( # lint-amnesty, pylint: disable=super-with-arguments
self._map_revision_to_branch(asset_key), **kwargs
)
def get_all_asset_metadata(self, course_key, asset_type, start=0, maxresults=-1, sort=None, **kwargs):
return super(DraftVersioningModuleStore, self).get_all_asset_metadata(
return super(DraftVersioningModuleStore, self).get_all_asset_metadata( # lint-amnesty, pylint: disable=super-with-arguments
self._map_revision_to_branch(course_key), asset_type, start, maxresults, sort, **kwargs
)
@@ -628,11 +628,11 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
Updates both the published and draft branches
"""
# if one call gets an exception, don't do the other call but pass on the exception
super(DraftVersioningModuleStore, self)._update_course_assets(
super(DraftVersioningModuleStore, self)._update_course_assets( # lint-amnesty, pylint: disable=super-with-arguments
user_id, self._map_revision_to_branch(asset_key, ModuleStoreEnum.RevisionOption.published_only),
update_function
)
super(DraftVersioningModuleStore, self)._update_course_assets(
super(DraftVersioningModuleStore, self)._update_course_assets( # lint-amnesty, pylint: disable=super-with-arguments
user_id, self._map_revision_to_branch(asset_key, ModuleStoreEnum.RevisionOption.draft_only),
update_function
)
@@ -646,17 +646,17 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
for asset_md in asset_metadata_list:
asset_key = asset_md.asset_id
asset_md.asset_id = self._map_revision_to_branch(asset_key, ModuleStoreEnum.RevisionOption.published_only)
super(DraftVersioningModuleStore, self).save_asset_metadata_list(asset_metadata_list, user_id, import_only)
super(DraftVersioningModuleStore, self).save_asset_metadata_list(asset_metadata_list, user_id, import_only) # lint-amnesty, pylint: disable=super-with-arguments
for asset_md in asset_metadata_list:
asset_key = asset_md.asset_id
asset_md.asset_id = self._map_revision_to_branch(asset_key, ModuleStoreEnum.RevisionOption.draft_only)
super(DraftVersioningModuleStore, self).save_asset_metadata_list(asset_metadata_list, user_id, import_only)
super(DraftVersioningModuleStore, self).save_asset_metadata_list(asset_metadata_list, user_id, import_only) # lint-amnesty, pylint: disable=super-with-arguments
# Change each asset key back to its original state.
for k in asset_keys:
asset_md.asset_id = k
def _find_course_asset(self, asset_key):
return super(DraftVersioningModuleStore, self)._find_course_asset(
return super(DraftVersioningModuleStore, self)._find_course_asset( # lint-amnesty, pylint: disable=super-with-arguments
self._map_revision_to_branch(asset_key)
)
@@ -664,7 +664,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
"""
Split specific lookup
"""
return super(DraftVersioningModuleStore, self)._find_course_assets(
return super(DraftVersioningModuleStore, self)._find_course_assets( # lint-amnesty, pylint: disable=super-with-arguments
self._map_revision_to_branch(course_key)
)
@@ -673,7 +673,7 @@ class DraftVersioningModuleStore(SplitMongoModuleStore, ModuleStoreDraftAndPubli
Copies to and from both branches
"""
for revision in [ModuleStoreEnum.RevisionOption.published_only, ModuleStoreEnum.RevisionOption.draft_only]:
super(DraftVersioningModuleStore, self).copy_all_asset_metadata(
super(DraftVersioningModuleStore, self).copy_all_asset_metadata( # lint-amnesty, pylint: disable=super-with-arguments
self._map_revision_to_branch(source_course_key, revision),
self._map_revision_to_branch(dest_course_key, revision),
user_id

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import copy
from collections import namedtuple
@@ -37,7 +37,7 @@ class SplitMongoKVS(InheritanceKeyValueStore):
(copied from a template block with copy_from_template)
"""
# deepcopy so that manipulations of fields does not pollute the source
super(SplitMongoKVS, self).__init__(copy.deepcopy(initial_values))
super(SplitMongoKVS, self).__init__(copy.deepcopy(initial_values)) # lint-amnesty, pylint: disable=super-with-arguments
self._definition = definition # either a DefinitionLazyLoader or the db id of the definition.
# if the db id, then the definition is presumed to be loaded into _fields
@@ -52,7 +52,7 @@ class SplitMongoKVS(InheritanceKeyValueStore):
self.aside_fields = aside_fields if aside_fields else {}
def get(self, key):
if key.block_family == XBlockAside.entry_point:
if key.block_family == XBlockAside.entry_point: # lint-amnesty, pylint: disable=no-else-raise
if key.scope not in self.VALID_SCOPES:
raise InvalidScopeError(key, self.VALID_SCOPES)
@@ -75,7 +75,7 @@ class SplitMongoKVS(InheritanceKeyValueStore):
if key.field_name not in self._fields:
if key.scope == Scope.parent:
return self.parent
if key.scope == Scope.children:
if key.scope == Scope.children: # lint-amnesty, pylint: disable=no-else-raise
# didn't find children in _fields; so, see if there's a default
raise KeyError()
elif key.scope == Scope.settings:
@@ -178,7 +178,7 @@ class SplitMongoKVS(InheritanceKeyValueStore):
if self._defaults and key.field_name in self._defaults:
return self._defaults[key.field_name]
# If not, try inheriting from a parent, then use the XBlock type's normal default value:
return super(SplitMongoKVS, self).default(key)
return super(SplitMongoKVS, self).default(key) # lint-amnesty, pylint: disable=super-with-arguments
def _load_definition(self):
"""

View File

@@ -1,4 +1,4 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import logging
import re
@@ -50,7 +50,7 @@ def rewrite_nonportable_content_links(source_course_id, dest_course_id, text):
try:
text = _prefix_only_url_replace_regex(asset_block_pattern).sub(portable_asset_link_subtitution, text)
except Exception as exc: # pylint: disable=broad-except
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", asset_block_pattern, text, str(exc))
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", asset_block_pattern, text, str(exc)) # lint-amnesty, pylint: disable=line-too-long
placeholder_category = 'cat_{}'.format(uuid.uuid4().hex)
usage_block_pattern = six.text_type(source_course_id.make_usage_key(placeholder_category, placeholder_id))
@@ -62,7 +62,7 @@ def rewrite_nonportable_content_links(source_course_id, dest_course_id, text):
try:
text = _prefix_only_url_replace_regex(jump_to_link_base).sub(portable_jump_to_link_substitution, text)
except Exception as exc: # pylint: disable=broad-except
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", jump_to_link_base, text, str(exc))
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", jump_to_link_base, text, str(exc)) # lint-amnesty, pylint: disable=line-too-long
# Also, there commonly is a set of link URL's used in the format:
# /courses/<org>/<course>/<name> which will be broken if migrated to a different course_id
@@ -73,9 +73,9 @@ def rewrite_nonportable_content_links(source_course_id, dest_course_id, text):
if source_course_id != dest_course_id:
try:
generic_courseware_link_base = u'/courses/{}/'.format(six.text_type(source_course_id))
text = re.sub(_prefix_only_url_replace_regex(generic_courseware_link_base), portable_asset_link_subtitution, text)
text = re.sub(_prefix_only_url_replace_regex(generic_courseware_link_base), portable_asset_link_subtitution, text) # lint-amnesty, pylint: disable=line-too-long
except Exception as exc: # pylint: disable=broad-except
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", source_course_id, text, str(exc))
logging.warning("Error producing regex substitution %r for text = %r.\n\nError msg = %s", source_course_id, text, str(exc)) # lint-amnesty, pylint: disable=line-too-long
return text

View File

@@ -11,7 +11,7 @@ from contextlib import contextmanager
from enum import Enum
from django.conf import settings
from django.contrib.auth.models import AnonymousUser, User
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
from django.db import connections
from django.test import TestCase
from django.test.utils import override_settings
@@ -245,7 +245,7 @@ class SignalIsolationMixin(object):
"You tried to enable signal '{}', but I don't recognize that "
"signal name. Did you mean one of these?: {}"
)
raise ValueError(err_msg.format(signal_name, all_signal_names))
raise ValueError(err_msg.format(signal_name, all_signal_names)) # lint-amnesty, pylint: disable=raise-missing-from
signal.enable()
@@ -398,7 +398,7 @@ class SharedModuleStoreTestCase(
for Django ORM models that will get cleaned up properly.
"""
# Tell Django to clean out all databases, not just default
databases = {alias for alias in connections}
databases = {alias for alias in connections} # lint-amnesty, pylint: disable=unnecessary-comprehension
@classmethod
@contextmanager
@@ -441,7 +441,7 @@ class SharedModuleStoreTestCase(
# OverrideFieldData.provider_classes is always reset to `None` so
# that they're recalculated for every test
OverrideFieldData.provider_classes = None
super(SharedModuleStoreTestCase, self).setUp()
super(SharedModuleStoreTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
class ModuleStoreTestCase(
@@ -487,7 +487,7 @@ class ModuleStoreTestCase(
CREATE_USER = True
# Tell Django to clean out all databases, not just default
databases = {alias for alias in connections}
databases = {alias for alias in connections} # lint-amnesty, pylint: disable=unnecessary-comprehension
@classmethod
def setUpClass(cls):
@@ -511,7 +511,7 @@ class ModuleStoreTestCase(
# that they're recalculated for every test
OverrideFieldData.provider_classes = None
super(ModuleStoreTestCase, self).setUp()
super(ModuleStoreTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.store = modulestore()

View File

@@ -26,7 +26,7 @@ from xmodule.course_module import Textbook
from xmodule.modulestore import ModuleStoreEnum, prefer_xmodules
from xmodule.modulestore.tests.sample_courses import TOY_BLOCK_INFO_TREE, default_block_info_tree
from xmodule.tabs import CourseTab
from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT
from xmodule.x_module import DEPRECATION_VSCOMPAT_EVENT # lint-amnesty, pylint: disable=unused-import
LOG = logging.getLogger(__name__)
@@ -46,7 +46,7 @@ class XModuleFactoryLock(threading.local):
will be called.
"""
def __init__(self):
super(XModuleFactoryLock, self).__init__()
super(XModuleFactoryLock, self).__init__() # lint-amnesty, pylint: disable=super-with-arguments
self._enabled = False
def enable(self):
@@ -86,7 +86,7 @@ class XModuleFactory(Factory):
model = Dummy
@lazy_attribute
def modulestore(self):
def modulestore(self): # lint-amnesty, pylint: disable=missing-function-docstring
msg = "XMODULE_FACTORY_LOCK not enabled. Please use ModuleStoreTestCase as your test baseclass."
assert XMODULE_FACTORY_LOCK.is_enabled(), msg
@@ -107,7 +107,7 @@ class CourseFactory(XModuleFactory):
# pylint: disable=unused-argument
@classmethod
def _create(cls, target_class, **kwargs):
def _create(cls, target_class, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Create and return a new course. For performance reasons, we do not emit
signals during this process, but if you need signals to run, you can
@@ -260,7 +260,7 @@ class LibraryFactory(XModuleFactory):
# pylint: disable=unused-argument
@classmethod
def _create(cls, target_class, **kwargs):
def _create(cls, target_class, **kwargs): # lint-amnesty, pylint: disable=arguments-differ
"""
Create a library with a unique name and key.
All class attributes (from this class and base classes) are automagically
@@ -291,18 +291,18 @@ class ItemFactory(XModuleFactory):
descriptive_tag = None
@lazy_attribute_sequence
def display_name(self, n):
def display_name(self, n): # lint-amnesty, pylint: disable=missing-function-docstring
if self.descriptive_tag:
return "{} {} - {}".format(self.category, n, self.descriptive_tag)
else:
return "{} {}".format(self.category, n)
@lazy_attribute
def location(self):
def location(self): # lint-amnesty, pylint: disable=missing-function-docstring
if self.display_name is None:
dest_name = uuid4().hex
else:
dest_name = self.display_name.replace(" ", "_")
dest_name = self.display_name.replace(" ", "_") # lint-amnesty, pylint: disable=no-member
new_location = self.parent_location.course_key.make_usage_key(
self.category,
@@ -311,7 +311,7 @@ class ItemFactory(XModuleFactory):
return new_location
@lazy_attribute
def parent_location(self):
def parent_location(self): # lint-amnesty, pylint: disable=missing-function-docstring
default_location = getattr(last_course, 'loc', None)
try:
parent = self.parent
@@ -326,7 +326,7 @@ class ItemFactory(XModuleFactory):
return parent.location
@classmethod
def _create(cls, target_class, **kwargs):
def _create(cls, target_class, **kwargs): # lint-amnesty, pylint: disable=arguments-differ, unused-argument
"""
Uses ``**kwargs``:
@@ -416,7 +416,7 @@ class ItemFactory(XModuleFactory):
store.update_item(course, user_id)
# parent and publish the item, so it can be accessed
if 'detached' not in module._class_tags:
if 'detached' not in module._class_tags: # lint-amnesty, pylint: disable=protected-access
parent.children.append(location)
store.update_item(parent, user_id)
if publish_item:
@@ -690,7 +690,7 @@ class CourseAboutFactory(XModuleFactory):
"""
@classmethod
def _create(cls, target_class, **kwargs): # pylint: disable=unused-argument
def _create(cls, target_class, **kwargs): # lint-amnesty, pylint: disable=arguments-differ, unused-argument
"""
Uses **kwargs:

View File

@@ -51,7 +51,7 @@ TOY_BLOCK_INFO_TREE = [
'Overview', "chapter", {"display_name": "Overview"}, [
BlockInfo(
"Toy_Videos", "videosequence", {
"xml_attributes": {"filename": ["", None]}, "display_name": "Toy Videos", "format": "Lecture Sequence"
"xml_attributes": {"filename": ["", None]}, "display_name": "Toy Videos", "format": "Lecture Sequence" # lint-amnesty, pylint: disable=line-too-long
}, [
BlockInfo(
"secret:toylab", "html", {
@@ -67,7 +67,7 @@ TOY_BLOCK_INFO_TREE = [
),
BlockInfo(
"toyjumpto", "html", {
"data": u"<a href=\"/jump_to_id/vertical_test\">This is a link to another page and some Chinese 四節比分和七年前</a> <p>Some more Chinese 四節比分和七年前</p>\n",
"data": u"<a href=\"/jump_to_id/vertical_test\">This is a link to another page and some Chinese 四節比分和七年前</a> <p>Some more Chinese 四節比分和七年前</p>\n", # lint-amnesty, pylint: disable=line-too-long
"xml_attributes": {"filename": ["html/toyjumpto.xml", "html/toyjumpto.xml"]}
}, []),
BlockInfo(
@@ -92,7 +92,7 @@ TOY_BLOCK_INFO_TREE = [
}, []),
BlockInfo(
"with_styling", "html", {
"data": "<p style=\"font:italic bold 72px/30px Georgia, serif; color: red; \">Red text here</p>",
"data": "<p style=\"font:italic bold 72px/30px Georgia, serif; color: red; \">Red text here</p>", # lint-amnesty, pylint: disable=line-too-long
"xml_attributes": {"filename": ["html/with_styling.xml", "html/with_styling.xml"]}
}, []),
BlockInfo(
@@ -109,7 +109,7 @@ TOY_BLOCK_INFO_TREE = [
"Welcome", "video", {"data": "", "youtube_id_1_0": "p2Q6BrNhdh8", "display_name": "Welcome"}, []
),
BlockInfo(
"video_123456789012", "video", {"data": "", "youtube_id_1_0": "p2Q6BrNhdh8", "display_name": "Test Video"}, []
"video_123456789012", "video", {"data": "", "youtube_id_1_0": "p2Q6BrNhdh8", "display_name": "Test Video"}, [] # lint-amnesty, pylint: disable=line-too-long
),
BlockInfo(
"video_4f66f493ac8f", "video", {"youtube_id_1_0": "p2Q6BrNhdh8"}, []

View File

@@ -36,7 +36,7 @@ class AssetStoreTestData(object):
now = datetime.now(pytz.utc)
user_id = 144
if six.PY2:
user_id_long = long(user_id)
user_id_long = long(user_id) # lint-amnesty, pylint: disable=undefined-variable
else:
user_id_long = int(user_id)
@@ -47,7 +47,7 @@ class AssetStoreTestData(object):
'edited_by', 'edited_by_email', 'edited_on', 'created_by', 'created_by_email', 'created_on',
'curr_version', 'prev_version'
)
# pylint: disable=bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value
all_asset_data = (
('pic1.jpg', 'EKMND332DDBK', 'pix/archive', False,
user_id_long, user_email, now + timedelta(seconds=10 * 1), user_id_long, user_email, now, '14', '13'),
@@ -76,8 +76,8 @@ class TestSortedAssetList(unittest.TestCase):
"""
def setUp(self):
super(TestSortedAssetList, self).setUp()
asset_list = [dict(list(zip(AssetStoreTestData.asset_fields, asset))) for asset in AssetStoreTestData.all_asset_data]
super(TestSortedAssetList, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
asset_list = [dict(list(zip(AssetStoreTestData.asset_fields, asset))) for asset in AssetStoreTestData.all_asset_data] # lint-amnesty, pylint: disable=line-too-long
self.sorted_asset_list_by_filename = SortedAssetList(iterable=asset_list)
self.sorted_asset_list_by_last_edit = SortedAssetList(iterable=asset_list, key=lambda x: x['edited_on'])
self.course_key = CourseLocator('org', 'course', 'run')
@@ -108,7 +108,7 @@ class TestMongoAssetMetadataStorage(TestCase):
}
def setUp(self):
super(TestMongoAssetMetadataStorage, self).setUp()
super(TestMongoAssetMetadataStorage, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.addTypeEqualityFunc(datetime, self._compare_datetimes)
self.addTypeEqualityFunc(AssetMetadata, self._compare_metadata)
@@ -124,9 +124,9 @@ class TestMongoAssetMetadataStorage(TestCase):
"""
So we can use the below date comparison
"""
if type(mdata1) != type(mdata2):
if type(mdata1) != type(mdata2): # lint-amnesty, pylint: disable=unidiomatic-typecheck
self.fail(self._formatMessage(msg, u"{} is not same type as {}".format(mdata1, mdata2)))
for attr in mdata1.ATTRS_ALLOWED_TO_UPDATE:
for attr in mdata1.ATTRS_ALLOWED_TO_UPDATE: # lint-amnesty, pylint: disable=redefined-outer-name
self.assertEqual(getattr(mdata1, attr), getattr(mdata2, attr), msg)
def _compare_datetimes(self, datetime1, datetime2, msg=None):
@@ -451,7 +451,7 @@ class TestMongoAssetMetadataStorage(TestCase):
"""
getting all things which are of type other than 'asset'
"""
# pylint: disable=bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value
with storebuilder.build() as (__, store):
course = CourseFactory.create(modulestore=store)
@@ -488,7 +488,7 @@ class TestMongoAssetMetadataStorage(TestCase):
"""
Save a list of asset metadata all at once.
"""
# pylint: disable=bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value
with storebuilder.build() as (__, store):
course = CourseFactory.create(modulestore=store)
@@ -528,7 +528,7 @@ class TestMongoAssetMetadataStorage(TestCase):
"""
Save a list of asset metadata all at once - but with one asset's metadata from a different course.
"""
# pylint: disable=bad-continuation
# lint-amnesty, pylint: disable=bad-continuation, bad-option-value
with storebuilder.build() as (__, store):
course1 = CourseFactory.create(modulestore=store)
course2 = CourseFactory.create(modulestore=store)

View File

@@ -59,17 +59,17 @@ class TestContentstore(unittest.TestCase):
"""
# since MongoModuleStore and MongoContentStore are basically assumed to be together, create this class
# as well
self.contentstore = MongoContentStore(HOST, DB, port=PORT)
self.contentstore = MongoContentStore(HOST, DB, port=PORT) # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.addCleanup(self.contentstore._drop_database) # pylint: disable=protected-access
AssetLocator.deprecated = deprecated
CourseLocator.deprecated = deprecated
self.course1_key = CourseLocator('test', 'asset_test', '2014_07')
self.course2_key = CourseLocator('test', 'asset_test2', '2014_07')
self.course1_key = CourseLocator('test', 'asset_test', '2014_07') # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course2_key = CourseLocator('test', 'asset_test2', '2014_07') # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course1_files = ['contains.sh', 'picture1.jpg', 'picture2.jpg']
self.course2_files = ['picture1.jpg', 'picture3.jpg', 'door_2.ogg']
self.course1_files = ['contains.sh', 'picture1.jpg', 'picture2.jpg'] # lint-amnesty, pylint: disable=attribute-defined-outside-init
self.course2_files = ['picture1.jpg', 'picture3.jpg', 'door_2.ogg'] # lint-amnesty, pylint: disable=attribute-defined-outside-init
def load_assets(course_key, files):
locked = False

View File

@@ -55,7 +55,7 @@ class CrossStoreXMLRoundtrip(CourseComparisonTest, PartitionTestCase):
"""
def setUp(self):
super(CrossStoreXMLRoundtrip, self).setUp()
super(CrossStoreXMLRoundtrip, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.export_dir = mkdtemp()
self.addCleanup(rmtree, self.export_dir, ignore_errors=True)
@@ -164,8 +164,8 @@ class CrossStoreXMLRoundtrip(CourseComparisonTest, PartitionTestCase):
with MongoContentstoreBuilder().build() as dest_content:
# Construct the modulestore for storing the second import (using the second contentstore)
with SPLIT_MODULESTORE_SETUP.build(contentstore=dest_content) as dest_store:
source_course_key = source_store.make_course_key('a', 'source', '2015_Fall')
dest_course_key = dest_store.make_course_key('a', 'dest', '2015_Fall')
source_course_key = source_store.make_course_key('a', 'source', '2015_Fall') # lint-amnesty, pylint: disable=no-member
dest_course_key = dest_store.make_course_key('a', 'dest', '2015_Fall') # lint-amnesty, pylint: disable=no-member
import_course_from_xml(
source_store,
@@ -186,7 +186,7 @@ class CrossStoreXMLRoundtrip(CourseComparisonTest, PartitionTestCase):
EXPORTED_COURSE_DIR_NAME,
)
source_course = source_store.get_course(source_course_key, depth=None, lazy=False)
source_course = source_store.get_course(source_course_key, depth=None, lazy=False) # lint-amnesty, pylint: disable=no-member
self.assertEqual(source_course.url_name, 'course')
@@ -206,6 +206,6 @@ class CrossStoreXMLRoundtrip(CourseComparisonTest, PartitionTestCase):
create_if_not_present=True,
)
dest_course = dest_store.get_course(dest_course_key, depth=None, lazy=False)
dest_course = dest_store.get_course(dest_course_key, depth=None, lazy=False) # lint-amnesty, pylint: disable=no-member
self.assertEqual(dest_course.url_name, 'course')

View File

@@ -19,7 +19,7 @@ class TestXBlock:
"""
An empty Xblock, to be used, when creating a block with mixins.
"""
pass
pass # lint-amnesty, pylint: disable=unnecessary-pass
@ddt.ddt
@@ -38,7 +38,7 @@ class TestInheritanceMixin(unittest.TestCase):
self.xblock = runtime.construct_xblock_from_class(
TestXBlock, ScopeIds('user', 'TestXBlock', 'def_id', 'usage_id')
)
super(TestInheritanceMixin, self).setUp()
super(TestInheritanceMixin, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
def add_submission_deadline_information(self, due_date, graceperiod, self_paced):
"""

View File

@@ -155,7 +155,7 @@ class TestLibraries(MixedSplitTestCase):
def test_get_libraries(self):
""" Test get_libraries() """
libraries = [LibraryFactory.create(modulestore=self.store) for _ in range(3)]
lib_dict = dict([(lib.location.library_key, lib) for lib in libraries])
lib_dict = dict([(lib.location.library_key, lib) for lib in libraries]) # lint-amnesty, pylint: disable=consider-using-dict-comprehension
lib_list = self.store.get_libraries()

View File

@@ -128,7 +128,7 @@ class CommonMixedModuleStoreSetup(CourseComparisonTest):
"""
Set up the database for testing
"""
super(CommonMixedModuleStoreSetup, self).setUp()
super(CommonMixedModuleStoreSetup, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.exclude_field(None, 'wiki_slug')
self.exclude_field(None, 'xml_attributes')
@@ -162,7 +162,7 @@ class CommonMixedModuleStoreSetup(CourseComparisonTest):
"""
# create course
with self.store.bulk_operations(course_key):
self.course = self.store.create_course(course_key.org, course_key.course, course_key.run, self.user_id)
self.course = self.store.create_course(course_key.org, course_key.course, course_key.run, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
if isinstance(self.course.id, CourseLocator):
self.course_locations[self.MONGO_COURSEID] = self.course.location
else:
@@ -267,7 +267,7 @@ class CommonMixedModuleStoreSetup(CourseComparisonTest):
"""
# set the default modulestore
store_configs = self.options['stores']
for index in range(len(store_configs)):
for index in range(len(store_configs)): # lint-amnesty, pylint: disable=consider-using-enumerate
if store_configs[index]['NAME'] == default:
if index > 0:
store_configs[index], store_configs[0] = store_configs[0], store_configs[index]
@@ -390,7 +390,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
with check_mongo_calls(max_find.pop(0), max_send):
self.assertTrue(self.store.has_item(self.problem_x1a_1))
self.assertTrue(self.store.has_item(self.problem_x1a_1)) # lint-amnesty, pylint: disable=no-member
# try negative cases
with check_mongo_calls(max_find.pop(0), max_send):
@@ -413,7 +413,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
with check_mongo_calls(max_find.pop(0), max_send):
self.assertIsNotNone(self.store.get_item(self.problem_x1a_1))
self.assertIsNotNone(self.store.get_item(self.problem_x1a_1)) # lint-amnesty, pylint: disable=no-member
# try negative cases
with check_mongo_calls(max_find.pop(0), max_send):
@@ -460,7 +460,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.assertIsNone(course_version)
blocks = self.store.get_items(self.course.id, qualifiers={'category': 'problem'})
blocks.append(self.store.get_item(self.problem_x1a_1))
blocks.append(self.store.get_item(self.problem_x1a_1)) # lint-amnesty, pylint: disable=no-member
self.assertEqual(len(blocks), 7)
for block in blocks:
self.assertEqual(block.course_version, course_version)
@@ -496,7 +496,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
items = self.store.get_items(course_key)
# Check items found are either course or about type
self.assertTrue(set(['course', 'about']).issubset(set([item.location.block_type for item in items])))
self.assertTrue(set(['course', 'about']).issubset(set([item.location.block_type for item in items]))) # lint-amnesty, pylint: disable=consider-using-set-comprehension
# Assert that about is a detached category found in get_items
self.assertIn(
[item.location.block_type for item in items if item.location.block_type == 'about'][0],
@@ -526,7 +526,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
items_in_tree = self.store.get_items(course_key, include_orphans=False)
# Check that course and about blocks are found in get_items
self.assertTrue(set(['course', 'about']).issubset(set([item.location.block_type for item in items_in_tree])))
self.assertTrue(set(['course', 'about']).issubset(set([item.location.block_type for item in items_in_tree]))) # lint-amnesty, pylint: disable=consider-using-set-comprehension
# Check orphan is found or not - this is based on mongo/split modulestore. It should be found in mongo.
self.assertEqual(orphan in [item.location for item in items_in_tree], orphan_in_items)
self.assertEqual(len(items_in_tree), expected_items_in_tree)
@@ -543,7 +543,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
"""
self.initdb(default_ms)
self._create_block_hierarchy()
problem = self.store.get_item(self.problem_x1a_1)
problem = self.store.get_item(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
# if following raised, then the test is really a noop, change it
self.assertNotEqual(problem.max_attempts, 2, "Default changed making test meaningless")
problem.max_attempts = 2
@@ -750,11 +750,11 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
locations = {
'grandparent': self.chapter_x,
'parent_sibling': self.sequential_x2,
'parent': self.sequential_x1,
'child_sibling': self.vertical_x1b,
'child': self.vertical_x1a,
'grandparent': self.chapter_x, # lint-amnesty, pylint: disable=no-member
'parent_sibling': self.sequential_x2, # lint-amnesty, pylint: disable=no-member
'parent': self.sequential_x1, # lint-amnesty, pylint: disable=no-member
'child_sibling': self.vertical_x1b, # lint-amnesty, pylint: disable=no-member
'child': self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
}
# Publish the vertical units
@@ -939,7 +939,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
if default_ms == ModuleStoreEnum.Type.mongo and mongo_uses_error_check(self.store):
max_find += 1
with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.writable_chapter_location.course_key):
with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, self.writable_chapter_location.course_key): # lint-amnesty, pylint: disable=line-too-long
with check_mongo_calls(max_find, max_send):
self.store.delete_item(self.writable_chapter_location, self.user_id)
@@ -1140,8 +1140,8 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
with check_mongo_calls(max_find, max_send):
parent = self.store.get_parent_location(self.problem_x1a_1)
self.assertEqual(parent, self.vertical_x1a)
parent = self.store.get_parent_location(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(parent, self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
def verify_get_parent_locations_results(self, expected_results):
"""
@@ -1207,12 +1207,12 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Publish the course.
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Move child problem_x1a_1 to vertical_y1a.
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
updated_item_location = self.store.update_item_parent(
item_location, new_parent_location, old_parent_location, self.user_id
)
@@ -1234,12 +1234,12 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Publish the course
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Move child problem_x1a_1 to vertical_y1a.
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
updated_item_location = self.store.update_item_parent(
item_location, new_parent_location, old_parent_location, self.user_id
)
@@ -1271,12 +1271,12 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Publish the course
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Move child problem_x1a_1 to vertical_y1a.
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
updated_item_location = self.store.update_item_parent(
item_location, new_parent_location, old_parent_location, self.user_id
)
@@ -1312,12 +1312,12 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Publish the course
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Move child problem_x1a_1 to vertical_y1a.
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
updated_item_location = self.store.update_item_parent(
item_location, new_parent_location, old_parent_location, self.user_id
)
@@ -1361,21 +1361,21 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Publish the course.
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Move child problem_x1a_1 to vertical_y1a.
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
problem = self.store.get_item(self.problem_x1a_1)
problem = self.store.get_item(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
orig_display_name = problem.display_name
# Change display name of problem and update just it.
problem.display_name = 'updated'
self.store.update_item(problem, self.user_id)
updated_problem = self.store.get_item(self.problem_x1a_1)
updated_problem = self.store.get_item(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(updated_problem.display_name, 'updated')
# Now, move from x1 to y1.
@@ -1394,7 +1394,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.store.revert_to_published(old_parent_location, self.user_id)
# Check that problem has the original name back.
reverted_problem = self.store.get_item(self.problem_x1a_1)
reverted_problem = self.store.get_item(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(orig_display_name, reverted_problem.display_name)
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
@@ -1407,14 +1407,14 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Create some children in vertical_x1a
problem_item2 = self.store.create_child(self.user_id, self.vertical_x1a, 'problem', 'Problem_Item2')
problem_item2 = self.store.create_child(self.user_id, self.vertical_x1a, 'problem', 'Problem_Item2') # lint-amnesty, pylint: disable=no-member
# Publish the course.
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
# Move problem_x1a_1 from x1 to y1.
updated_item_location = self.store.update_item_parent(
@@ -1430,7 +1430,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# Check that problem_item2 is still present in vertical_x1a
problem_item2 = self.store.get_item(problem_item2.location)
self.assertEqual(problem_item2.parent, self.vertical_x1a)
self.assertEqual(problem_item2.parent, self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.assertIn(problem_item2.location, problem_item2.get_parent().children)
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
@@ -1444,11 +1444,11 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Create some children in vertical_x1a
problem_item2 = self.store.create_child(self.user_id, self.vertical_x1a, 'problem', 'Problem_Item2')
problem_item2 = self.store.create_child(self.user_id, self.vertical_x1a, 'problem', 'Problem_Item2') # lint-amnesty, pylint: disable=no-member
orig_display_name = problem_item2.display_name
# Publish the course.
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Edit problem_item2.
problem_item2.display_name = 'updated'
@@ -1457,9 +1457,9 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
updated_problem2 = self.store.get_item(problem_item2.location)
self.assertEqual(updated_problem2.display_name, 'updated')
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
# Move problem_x1a_1 from x1 to y1.
updated_item_location = self.store.update_item_parent(
@@ -1491,19 +1491,19 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# Create some children in vertical_x1a
problem_item2 = self.store.create_child(self.user_id, self.vertical_x1a, 'problem', 'Problem_Item2')
orig_display_name = problem_item2.display_name
problem_item2 = self.store.create_child(self.user_id, self.vertical_x1a, 'problem', 'Problem_Item2') # lint-amnesty, pylint: disable=no-member
orig_display_name = problem_item2.display_name # lint-amnesty, pylint: disable=unused-variable
# Publish the course.
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
# Now delete other problem problem_item2.
self.store.delete_item(problem_item2.location, self.user_id)
# Move child problem_x1a_1 to vertical_y1a.
item_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
item_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
# Move problem_x1a_1 from x1 to y1.
updated_item_location = self.store.update_item_parent(
@@ -1522,7 +1522,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# Check that problem_item2 is also back in vertical_x1a
problem_item2 = self.store.get_item(problem_item2.location)
self.assertEqual(problem_item2.parent, self.vertical_x1a)
self.assertEqual(problem_item2.parent, self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.assertIn(problem_item2.location, problem_item2.get_parent().children)
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
@@ -1531,17 +1531,17 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# publish the course
self.course = self.store.publish(self.course.location, self.user_id)
self.course = self.store.publish(self.course.location, self.user_id) # lint-amnesty, pylint: disable=attribute-defined-outside-init
with self.store.bulk_operations(self.course.id):
# make drafts of verticals
self.store.convert_to_draft(self.vertical_x1a, self.user_id)
self.store.convert_to_draft(self.vertical_y1a, self.user_id)
self.store.convert_to_draft(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
self.store.convert_to_draft(self.vertical_y1a, self.user_id) # lint-amnesty, pylint: disable=no-member
# move child problem_x1a_1 to vertical_y1a
child_to_move_location = self.problem_x1a_1
new_parent_location = self.vertical_y1a
old_parent_location = self.vertical_x1a
child_to_move_location = self.problem_x1a_1 # lint-amnesty, pylint: disable=no-member
new_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_x1a # lint-amnesty, pylint: disable=no-member
with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred):
old_parent = self.store.get_item(child_to_move_location).get_parent()
@@ -1585,11 +1585,11 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.store.publish(self.course.location, self.user_id)
# make draft of vertical
self.store.convert_to_draft(self.vertical_y1a, self.user_id)
self.store.convert_to_draft(self.vertical_y1a, self.user_id) # lint-amnesty, pylint: disable=no-member
# delete child problem_y1a_1
child_to_delete_location = self.problem_y1a_1
old_parent_location = self.vertical_y1a
child_to_delete_location = self.problem_y1a_1 # lint-amnesty, pylint: disable=no-member
old_parent_location = self.vertical_y1a # lint-amnesty, pylint: disable=no-member
self.store.delete_item(child_to_delete_location, self.user_id)
self.verify_get_parent_locations_results([
@@ -1624,13 +1624,13 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
mongo_store = self.store._get_modulestore_for_courselike(course_id) # pylint: disable=protected-access
# add another parent (unit) "vertical_x1b" for problem "problem_x1a_1"
mongo_store.collection.update_one(
self.vertical_x1b.to_deprecated_son('_id.'),
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}}
self.vertical_x1b.to_deprecated_son('_id.'), # lint-amnesty, pylint: disable=no-member
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}} # lint-amnesty, pylint: disable=no-member
)
# convert first parent (unit) "vertical_x1a" of problem "problem_x1a_1" to draft
self.store.convert_to_draft(self.vertical_x1a, self.user_id)
item = self.store.get_item(self.vertical_x1a)
self.store.convert_to_draft(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
item = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.assertTrue(self.store.has_published_version(item))
# now problem "problem_x1a_1" has 3 parents [vertical_x1a (draft),
@@ -1639,8 +1639,8 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# published parent "vertical_x1a" without raising "AssertionError" for
# problem location revision
with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course_id):
parent = mongo_store.get_parent_location(self.problem_x1a_1)
self.assertEqual(parent, self.vertical_x1a)
parent = mongo_store.get_parent_location(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(parent, self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
# Draft:
# Problem path:
@@ -1663,10 +1663,10 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
should_work = (
(self.problem_x1a_2,
(course_key, u"Chapter_x", u"Sequential_x1", u'Vertical_x1a', '1', self.problem_x1a_2)),
(self.chapter_x,
(course_key, "Chapter_x", None, None, None, self.chapter_x)),
(self.problem_x1a_2, # lint-amnesty, pylint: disable=no-member
(course_key, u"Chapter_x", u"Sequential_x1", u'Vertical_x1a', '1', self.problem_x1a_2)), # lint-amnesty, pylint: disable=no-member
(self.chapter_x, # lint-amnesty, pylint: disable=no-member
(course_key, "Chapter_x", None, None, None, self.chapter_x)), # lint-amnesty, pylint: disable=no-member
)
for location, expected in should_work:
@@ -1715,29 +1715,29 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.initdb(default_ms)
self._create_block_hierarchy()
vertical = self.store.get_item(self.vertical_x1a)
vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
vertical_children_num = len(vertical.children)
self.store.publish(self.course.location, self.user_id)
self.assertFalse(self._has_changes(self.vertical_x1a))
self.assertFalse(self._has_changes(self.vertical_x1a)) # lint-amnesty, pylint: disable=no-member
# delete leaf problem (will make parent vertical a draft)
self.store.delete_item(self.problem_x1a_1, self.user_id)
self.assertTrue(self._has_changes(self.vertical_x1a))
self.store.delete_item(self.problem_x1a_1, self.user_id) # lint-amnesty, pylint: disable=no-member
self.assertTrue(self._has_changes(self.vertical_x1a)) # lint-amnesty, pylint: disable=no-member
draft_parent = self.store.get_item(self.vertical_x1a)
draft_parent = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.assertEqual(vertical_children_num - 1, len(draft_parent.children))
published_parent = self.store.get_item(
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
revision=ModuleStoreEnum.RevisionOption.published_only
)
self.assertEqual(vertical_children_num, len(published_parent.children))
self.store.revert_to_published(self.vertical_x1a, self.user_id)
reverted_parent = self.store.get_item(self.vertical_x1a)
self.store.revert_to_published(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
reverted_parent = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.assertEqual(vertical_children_num, len(published_parent.children))
self.assertBlocksEqualByFields(reverted_parent, published_parent)
self.assertFalse(self._has_changes(self.vertical_x1a))
self.assertFalse(self._has_changes(self.vertical_x1a)) # lint-amnesty, pylint: disable=no-member
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_revert_to_published_root_published(self, default_ms):
@@ -1748,15 +1748,15 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
self.store.publish(self.course.location, self.user_id)
problem = self.store.get_item(self.problem_x1a_1)
problem = self.store.get_item(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
orig_display_name = problem.display_name
# Change display name of problem and update just it (so parent remains published)
problem.display_name = "updated before calling revert"
self.store.update_item(problem, self.user_id)
self.store.revert_to_published(self.vertical_x1a, self.user_id)
self.store.revert_to_published(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
reverted_problem = self.store.get_item(self.problem_x1a_1)
reverted_problem = self.store.get_item(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(orig_display_name, reverted_problem.display_name)
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
@@ -1768,9 +1768,9 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
self.store.publish(self.course.location, self.user_id)
orig_vertical = self.store.get_item(self.vertical_x1a)
self.store.revert_to_published(self.vertical_x1a, self.user_id)
reverted_vertical = self.store.get_item(self.vertical_x1a)
orig_vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.store.revert_to_published(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
reverted_vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
self.assertBlocksEqualByFields(orig_vertical, reverted_vertical)
@@ -1782,7 +1782,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.initdb(default_ms)
self._create_block_hierarchy()
with self.assertRaises(InvalidVersionError):
self.store.revert_to_published(self.vertical_x1a, self.user_id)
self.store.revert_to_published(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
@ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split)
def test_revert_to_published_direct_only(self, default_ms):
@@ -1791,9 +1791,9 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
"""
self.initdb(default_ms)
self._create_block_hierarchy()
num_children = len(self.store.get_item(self.sequential_x1).children)
self.store.revert_to_published(self.sequential_x1, self.user_id)
reverted_parent = self.store.get_item(self.sequential_x1)
num_children = len(self.store.get_item(self.sequential_x1).children) # lint-amnesty, pylint: disable=no-member
self.store.revert_to_published(self.sequential_x1, self.user_id) # lint-amnesty, pylint: disable=no-member
reverted_parent = self.store.get_item(self.sequential_x1) # lint-amnesty, pylint: disable=no-member
# It does not discard the child vertical, even though that child is a draft (with no published version)
self.assertEqual(num_children, len(reverted_parent.children))
@@ -1808,7 +1808,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# Get children of a vertical as a set.
# We will use this set as a basis for content comparision in this test.
original_vertical = self.store.get_item(self.vertical_x1a)
original_vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
original_vertical_children = set(original_vertical.children)
# Find the version_guid of our course by diving into Split Mongo.
@@ -1823,16 +1823,16 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
original_version_guid,
self.user_id,
)
noop_reset_vertical = self.store.get_item(self.vertical_x1a)
noop_reset_vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
assert set(noop_reset_vertical.children) == original_vertical_children
# Delete a problem from the vertical and publish.
# Vertical should have one less problem than before.
self.store.delete_item(self.problem_x1a_1, self.user_id)
self.store.delete_item(self.problem_x1a_1, self.user_id) # lint-amnesty, pylint: disable=no-member
self.store.publish(self.course.location, self.user_id)
modified_vertical = self.store.get_item(self.vertical_x1a)
modified_vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
assert set(modified_vertical.children) == (
original_vertical_children - {self.problem_x1a_1}
original_vertical_children - {self.problem_x1a_1} # lint-amnesty, pylint: disable=no-member
)
# Add a couple more children to the vertical.
@@ -1840,14 +1840,14 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# We want to make sure we can restore from something a few versions back.
self.store.create_child(
self.user_id,
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
'problem',
block_id='new_child1',
)
self.store.publish(self.course.location, self.user_id)
self.store.create_child(
self.user_id,
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
'problem',
block_id='new_child2',
)
@@ -1857,7 +1857,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# We want to make sure that this works with a dirty draft branch.
self.store.create_child(
self.user_id,
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
'problem',
block_id='new_child3',
)
@@ -1869,7 +1869,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
original_version_guid,
self.user_id,
)
restored_vertical = self.store.get_item(self.vertical_x1a)
restored_vertical = self.store.get_item(self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
assert set(restored_vertical.children) == original_vertical_children
def _get_split_modulestore(self):
@@ -1942,8 +1942,8 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# test that problem "problem_x1a_1" has only one published parent
mongo_store = self.store._get_modulestore_for_courselike(course_id) # pylint: disable=protected-access
with self.store.branch_setting(ModuleStoreEnum.Branch.published_only, course_id):
parent = mongo_store.get_parent_location(self.problem_x1a_1)
self.assertEqual(parent, self.vertical_x1a)
parent = mongo_store.get_parent_location(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(parent, self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
# add some published orphans
orphan_sequential = course_id.make_usage_key('sequential', 'OrphanSequential')
@@ -1965,29 +1965,29 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# add orphan vertical and sequential as another parents of problem "problem_x1a_1"
mongo_store.collection.update_one(
orphan_sequential.to_deprecated_son('_id.'),
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}}
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}} # lint-amnesty, pylint: disable=no-member
)
mongo_store.collection.update_one(
orphan_vertical.to_deprecated_son('_id.'),
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}}
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}} # lint-amnesty, pylint: disable=no-member
)
# test that "get_parent_location" method of published branch still returns the correct non-orphan parent for
# problem "problem_x1a_1" since the two other parents are orphans
with self.store.branch_setting(ModuleStoreEnum.Branch.published_only, course_id):
parent = mongo_store.get_parent_location(self.problem_x1a_1)
self.assertEqual(parent, self.vertical_x1a)
parent = mongo_store.get_parent_location(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
self.assertEqual(parent, self.vertical_x1a) # lint-amnesty, pylint: disable=no-member
# now add valid published vertical as another parent of problem
mongo_store.collection.update_one(
self.sequential_x1.to_deprecated_son('_id.'),
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}}
self.sequential_x1.to_deprecated_son('_id.'), # lint-amnesty, pylint: disable=no-member
{'$push': {'definition.children': six.text_type(self.problem_x1a_1)}} # lint-amnesty, pylint: disable=no-member
)
# now check that "get_parent_location" method of published branch raises "ReferentialIntegrityError" for
# problem "problem_x1a_1" since it has now 2 valid published parents
with self.store.branch_setting(ModuleStoreEnum.Branch.published_only, course_id):
self.assertTrue(self.store.has_item(self.problem_x1a_1))
self.assertTrue(self.store.has_item(self.problem_x1a_1)) # lint-amnesty, pylint: disable=no-member
with self.assertRaises(ReferentialIntegrityError):
self.store.get_parent_location(self.problem_x1a_1)
self.store.get_parent_location(self.problem_x1a_1) # lint-amnesty, pylint: disable=no-member
@ddt.data(ModuleStoreEnum.Type.mongo)
def test_create_item_from_parent_location(self, default_ms):
@@ -2072,24 +2072,24 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
# publish
self.store.publish(self.course.location, self.user_id)
published_xblock = self.store.get_item(
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
revision=ModuleStoreEnum.RevisionOption.published_only
)
self.assertIsNotNone(published_xblock)
# unpublish
with check_mongo_calls(max_find, max_send):
self.store.unpublish(self.vertical_x1a, self.user_id)
self.store.unpublish(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
with self.assertRaises(ItemNotFoundError):
self.store.get_item(
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
revision=ModuleStoreEnum.RevisionOption.published_only
)
# make sure draft version still exists
draft_xblock = self.store.get_item(
self.vertical_x1a,
self.vertical_x1a, # lint-amnesty, pylint: disable=no-member
revision=ModuleStoreEnum.RevisionOption.draft_only
)
self.assertIsNotNone(draft_xblock)
@@ -2106,7 +2106,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self._create_block_hierarchy()
# start off as Private
item = self.store.create_child(self.user_id, self.writable_chapter_location, 'problem', 'test_compute_publish_state')
item = self.store.create_child(self.user_id, self.writable_chapter_location, 'problem', 'test_compute_publish_state') # lint-amnesty, pylint: disable=line-too-long
item_location = item.location
with check_mongo_calls(max_find, max_send):
self.assertFalse(self.store.has_published_version(item))
@@ -2405,7 +2405,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.initdb(default_ms)
self._create_block_hierarchy()
problem_location = self.problem_x1a_1.for_branch(None)
problem_location = self.problem_x1a_1.for_branch(None) # lint-amnesty, pylint: disable=no-member
problem_original_name = 'Problem_x1a_1'
course_key = problem_location.course_key
@@ -2443,7 +2443,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup):
self.store.get_item(problem_location)
# PUBLISH the problem
self.store.publish(self.vertical_x1a, self.user_id)
self.store.publish(self.vertical_x1a, self.user_id) # lint-amnesty, pylint: disable=no-member
self.store.publish(problem_location, self.user_id)
# verify Published problem
@@ -3048,7 +3048,7 @@ class TestPublishOverExportImport(CommonMixedModuleStoreSetup):
"""
Set up the database for testing
"""
super(TestPublishOverExportImport, self).setUp()
super(TestPublishOverExportImport, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
self.user_id = ModuleStoreEnum.UserID.test
self.export_dir = mkdtemp()
@@ -3657,7 +3657,7 @@ class TestAsidesWithMixedModuleStore(CommonMixedModuleStoreSetup):
"""
Setup environment for testing
"""
super(TestAsidesWithMixedModuleStore, self).setUp()
super(TestAsidesWithMixedModuleStore, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments
key_store = DictKeyValueStore()
field_data = KvsFieldData(key_store)
self.runtime = TestRuntime(services={'field-data': field_data})

View File

@@ -5,7 +5,7 @@ This file should potentially be renamed "utilties" since this file contains no t
"""
def check_has_course_method(modulestore, locator, locator_key_fields):
def check_has_course_method(modulestore, locator, locator_key_fields): # lint-amnesty, pylint: disable=missing-function-docstring
error_message = "Called has_course with query {0} and ignore_case is {1}."
for ignore_case in [True, False]:

Some files were not shown because too many files have changed in this diff Show More