From a027f367240a4ba775d69fa31756100e2018b10e Mon Sep 17 00:00:00 2001 From: 0x29a Date: Wed, 28 Dec 2022 17:05:49 +0100 Subject: [PATCH] refactor: rename module -> block within xmodule --- .../management/commands/import.py | 2 +- .../commands/import_content_library.py | 2 +- .../contentstore/management/commands/xlint.py | 2 +- cms/djangoapps/contentstore/tasks.py | 2 +- .../views/tests/test_import_export.py | 20 +- common/test/data/conditional/README.md | 4 +- common/test/data/simple/README.md | 4 +- common/test/data/simple_with_draft/README.md | 4 +- .../courseware/management/commands/import.py | 2 +- lms/djangoapps/courseware/model_data.py | 2 +- .../courseware/tests/test_video_mongo.py | 10 +- .../completion_integration/test_services.py | 12 +- xmodule/capa/tests/helpers.py | 2 +- xmodule/capa/util.py | 2 +- xmodule/conditional_block.py | 40 +- xmodule/course_block.py | 4 +- xmodule/error_block.py | 16 +- xmodule/graders.py | 4 +- xmodule/html_block.py | 6 +- xmodule/library_root_xblock.py | 2 +- xmodule/lti_2_util.py | 2 +- xmodule/mako_block.py | 2 +- xmodule/modulestore/__init__.py | 4 +- xmodule/modulestore/inheritance.py | 14 +- xmodule/modulestore/mixed.py | 2 +- xmodule/modulestore/mongo/base.py | 66 +- xmodule/modulestore/mongo/draft.py | 60 +- xmodule/modulestore/search.py | 12 +- .../split_mongo/caching_descriptor_system.py | 33 +- xmodule/modulestore/split_mongo/split.py | 28 +- xmodule/modulestore/store_utilities.py | 4 +- xmodule/modulestore/tests/factories.py | 18 +- .../tests/test_mixed_modulestore.py | 12 +- .../tests/test_split_modulestore.py | 76 +- .../modulestore/tests/test_store_utilities.py | 6 +- xmodule/modulestore/tests/test_xml.py | 10 +- .../modulestore/tests/test_xml_importer.py | 12 +- xmodule/modulestore/xml.py | 72 +- xmodule/modulestore/xml_exporter.py | 34 +- xmodule/modulestore/xml_importer.py | 226 +++--- xmodule/progress.py | 6 +- xmodule/randomize_block.py | 6 +- xmodule/raw_block.py | 4 +- xmodule/seq_block.py | 4 +- xmodule/split_test_block.py | 16 +- xmodule/studio_editable.py | 4 +- xmodule/template_block.py | 2 +- xmodule/tests/helpers.py | 6 +- xmodule/tests/test_annotatable_block.py | 2 +- xmodule/tests/test_capa_block.py | 741 +++++++++--------- xmodule/tests/test_conditional.py | 100 +-- xmodule/tests/test_course_block.py | 10 +- xmodule/tests/test_delay_between_attempts.py | 68 +- xmodule/tests/test_export.py | 2 +- xmodule/tests/test_html_block.py | 46 +- xmodule/tests/test_import.py | 44 +- xmodule/tests/test_library_content.py | 16 +- xmodule/tests/test_lti20_unit.py | 120 +-- xmodule/tests/test_lti_unit.py | 124 +-- xmodule/tests/test_poll.py | 10 +- xmodule/tests/test_randomize_block.py | 2 +- xmodule/tests/test_sequence.py | 6 +- xmodule/tests/test_split_test_block.py | 6 +- xmodule/tests/test_transcripts_utils.py | 2 +- xmodule/tests/test_vertical.py | 4 +- xmodule/tests/test_video.py | 26 +- xmodule/unit_block.py | 2 +- xmodule/vertical_block.py | 2 +- xmodule/video_block/transcripts_utils.py | 36 +- xmodule/video_block/video_block.py | 4 +- xmodule/video_block/video_utils.py | 14 +- xmodule/word_cloud_block.py | 2 +- xmodule/x_module.py | 12 +- 73 files changed, 1141 insertions(+), 1143 deletions(-) diff --git a/cms/djangoapps/contentstore/management/commands/import.py b/cms/djangoapps/contentstore/management/commands/import.py index e2a54731c9..4ff9e7ce8d 100644 --- a/cms/djangoapps/contentstore/management/commands/import.py +++ b/cms/djangoapps/contentstore/management/commands/import.py @@ -64,7 +64,7 @@ class Command(BaseCommand): mstore = modulestore() course_items = import_course_from_xml( - mstore, ModuleStoreEnum.UserID.mgmt_command, data_dir, source_dirs, load_error_modules=False, + mstore, ModuleStoreEnum.UserID.mgmt_command, data_dir, source_dirs, load_error_blocks=False, static_content_store=contentstore(), verbose=True, do_import_static=do_import_static, do_import_python_lib=do_import_python_lib, create_if_not_present=True, diff --git a/cms/djangoapps/contentstore/management/commands/import_content_library.py b/cms/djangoapps/contentstore/management/commands/import_content_library.py index 60f33ffdf7..782db49880 100644 --- a/cms/djangoapps/contentstore/management/commands/import_content_library.py +++ b/cms/djangoapps/contentstore/management/commands/import_content_library.py @@ -87,7 +87,7 @@ class Command(BaseCommand): import_library_from_xml( modulestore(), user.id, settings.GITHUB_REPO_ROOT, [rel_xml_path], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore(), target_id=courselike_key ) diff --git a/cms/djangoapps/contentstore/management/commands/xlint.py b/cms/djangoapps/contentstore/management/commands/xlint.py index 655a2af01e..d7e93d44de 100644 --- a/cms/djangoapps/contentstore/management/commands/xlint.py +++ b/cms/djangoapps/contentstore/management/commands/xlint.py @@ -31,4 +31,4 @@ class Command(BaseCommand): data=data_dir, courses=source_dirs)) - perform_xlint(data_dir, source_dirs, load_error_modules=False) + perform_xlint(data_dir, source_dirs, load_error_blocks=False) diff --git a/cms/djangoapps/contentstore/tasks.py b/cms/djangoapps/contentstore/tasks.py index af0c6ea9d1..5463227a43 100644 --- a/cms/djangoapps/contentstore/tasks.py +++ b/cms/djangoapps/contentstore/tasks.py @@ -635,7 +635,7 @@ def import_olx(self, user_id, course_key_string, archive_path, archive_name, lan courselike_items = import_func( modulestore(), user.id, settings.GITHUB_REPO_ROOT, [dirpath], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore(), target_id=courselike_key, verbose=True, diff --git a/cms/djangoapps/contentstore/views/tests/test_import_export.py b/cms/djangoapps/contentstore/views/tests/test_import_export.py index 04d34ee4df..d1cd931b64 100644 --- a/cms/djangoapps/contentstore/views/tests/test_import_export.py +++ b/cms/djangoapps/contentstore/views/tests/test_import_export.py @@ -51,7 +51,7 @@ from xmodule.modulestore.xml_importer import ( # lint-amnesty, pylint: disable= ErrorReadingFileException, import_course_from_xml, import_library_from_xml, - ModuleFailedToImport, + BlockFailedToImport, ) TASK_LOGGER = 'cms.djangoapps.contentstore.tasks.LOGGER' @@ -460,7 +460,7 @@ class ImportTestCase(CourseTestCase): self.user.id, settings.GITHUB_REPO_ROOT, [extract_dir_relative / 'library'], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore(), target_id=lib_key ) @@ -505,7 +505,7 @@ class ImportTestCase(CourseTestCase): self.user.id, settings.GITHUB_REPO_ROOT, [extract_dir_relative / 'library'], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore(), target_id=lib_key ) @@ -540,7 +540,7 @@ class ImportTestCase(CourseTestCase): [extract_dir_relative / 'library'], static_content_store=source_content, target_id=source_library_key, - load_error_modules=False, + load_error_blocks=False, raise_on_failure=True, create_if_not_present=True, ) @@ -639,7 +639,7 @@ class ImportTestCase(CourseTestCase): ), (DuplicateCourseError("foo", "foobar"), 'Cannot create course foo, which duplicates foobar'), (ErrorReadingFileException("assets.xml"), "Error while reading assets.xml. Check file for XML errors."), - (ModuleFailedToImport("Unit 1", "foo/bar"), "Failed to import module: Unit 1 at location: foo/bar"), + (BlockFailedToImport("Unit 1", "foo/bar"), "Failed to import block: Unit 1 at location: foo/bar"), ) @ddt.unpack def test_import_failure_is_descriptive_for_known_failures(self, exc, expected_mesg, mocked_import, mocked_log): @@ -840,7 +840,7 @@ class ExportTestCase(CourseTestCase): self.assertNotIn('ExportOutput', result) self.assertIn('ExportError', result) error = result['ExportError'] - self.assertIn('Unable to create xml for module', error['raw_error_msg']) + self.assertIn('Unable to create xml for block', error['raw_error_msg']) self.assertIn(expected_text, error['edit_unit_url']) def test_library_export(self): @@ -1033,7 +1033,7 @@ class TestLibraryImportExport(CourseTestCase): ['library_empty_problem'], static_content_store=contentstore(), target_id=source_library1_key, - load_error_modules=False, + load_error_blocks=False, raise_on_failure=True, create_if_not_present=True, ) @@ -1057,7 +1057,7 @@ class TestLibraryImportExport(CourseTestCase): ['exported_source_library'], static_content_store=contentstore(), target_id=source_library2_key, - load_error_modules=False, + load_error_blocks=False, raise_on_failure=True, create_if_not_present=True, ) @@ -1184,7 +1184,7 @@ class TestCourseExportImport(LibraryTestCase): ['exported_source_course'], static_content_store=contentstore(), target_id=dest_course.location.course_key, - load_error_modules=False, + load_error_blocks=False, raise_on_failure=True, create_if_not_present=True, ) @@ -1314,7 +1314,7 @@ class TestCourseExportImportProblem(CourseTestCase): ['exported_source_course'], static_content_store=contentstore(), target_id=dest_course.location.course_key, - load_error_modules=False, + load_error_blocks=False, raise_on_failure=True, create_if_not_present=True, ) diff --git a/common/test/data/conditional/README.md b/common/test/data/conditional/README.md index f44ef84fe8..4dd46d70d7 100644 --- a/common/test/data/conditional/README.md +++ b/common/test/data/conditional/README.md @@ -1,4 +1,4 @@ -Course for testing conditional module. +Course for testing conditional block. Note that 'i4x://edX/different_course/html/for_testing_import_rewrites' in sources is only present for testing that import does NOT rewrite references to @@ -6,4 +6,4 @@ courses that differ from the original course being imported. It is not expected that i4x://edX/different_course/html/for_testing_import_rewrites will render. - + diff --git a/common/test/data/simple/README.md b/common/test/data/simple/README.md index 69ff6b4ed0..e4e63fca56 100644 --- a/common/test/data/simple/README.md +++ b/common/test/data/simple/README.md @@ -1,2 +1,2 @@ -This is a simple, but non-trivial, course using multiple module types and some nested structure. - +This is a simple, but non-trivial, course using multiple block types and some nested structure. + diff --git a/common/test/data/simple_with_draft/README.md b/common/test/data/simple_with_draft/README.md index 69ff6b4ed0..e4e63fca56 100644 --- a/common/test/data/simple_with_draft/README.md +++ b/common/test/data/simple_with_draft/README.md @@ -1,2 +1,2 @@ -This is a simple, but non-trivial, course using multiple module types and some nested structure. - +This is a simple, but non-trivial, course using multiple block types and some nested structure. + diff --git a/lms/djangoapps/courseware/management/commands/import.py b/lms/djangoapps/courseware/management/commands/import.py index 92fba632dd..7ebb267951 100644 --- a/lms/djangoapps/courseware/management/commands/import.py +++ b/lms/djangoapps/courseware/management/commands/import.py @@ -64,7 +64,7 @@ class Command(BaseCommand): mstore = modulestore() course_items = import_course_from_xml( - mstore, ModuleStoreEnum.UserID.mgmt_command, data_dir, source_dirs, load_error_modules=False, + mstore, ModuleStoreEnum.UserID.mgmt_command, data_dir, source_dirs, load_error_blocks=False, static_content_store=contentstore(), verbose=True, do_import_static=do_import_static, do_import_python_lib=do_import_python_lib, create_if_not_present=True, diff --git a/lms/djangoapps/courseware/model_data.py b/lms/djangoapps/courseware/model_data.py index 029706c50b..26578f286c 100644 --- a/lms/djangoapps/courseware/model_data.py +++ b/lms/djangoapps/courseware/model_data.py @@ -749,7 +749,7 @@ class FieldDataCache: if depth is None or depth > 0: new_depth = depth - 1 if depth is not None else depth - for child in descriptor.get_children() + descriptor.get_required_module_descriptors(): + for child in descriptor.get_children() + descriptor.get_required_block_descriptors(): descriptors.extend(get_child_descriptors(child, new_depth, descriptor_filter)) return descriptors diff --git a/lms/djangoapps/courseware/tests/test_video_mongo.py b/lms/djangoapps/courseware/tests/test_video_mongo.py index 3a2b460065..9f51f06c01 100644 --- a/lms/djangoapps/courseware/tests/test_video_mongo.py +++ b/lms/djangoapps/courseware/tests/test_video_mongo.py @@ -1786,7 +1786,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): Test that import val data internal works as expected. """ create_profile('mobile') - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) edx_video_id = 'test_edx_video_id' sub_id = '0CzPOIIdUsA' @@ -1889,7 +1889,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): """ xml_data = """""" xml_object = etree.fromstring(xml_data) - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) id_generator = Mock() # Verify edx_video_id is empty before. @@ -1926,7 +1926,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): val_transcript_provider=val_transcript_provider ) xml_object = etree.fromstring(xml_data) - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) id_generator = Mock() # Create static directory in import file system and place transcript files inside it. @@ -2032,7 +2032,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): edx_video_id = 'test_edx_video_id' language_code = 'en' - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) id_generator = Mock() # Create static directory in import file system and place transcript files inside it. @@ -2101,7 +2101,7 @@ class VideoBlockTest(TestCase, VideoBlockTestBase): def test_import_val_data_invalid(self): create_profile('mobile') - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) # Negative file_size is invalid xml_data = """ diff --git a/openedx/tests/completion_integration/test_services.py b/openedx/tests/completion_integration/test_services.py index 5a8287f8f6..d7bc197d95 100644 --- a/openedx/tests/completion_integration/test_services.py +++ b/openedx/tests/completion_integration/test_services.py @@ -117,24 +117,24 @@ class CompletionServiceTestCase(CompletionWaffleTestMixin, SharedModuleStoreTest completion=0.75, ) - def _bind_course_block(self, module): + def _bind_course_block(self, block): """ - Bind a module (part of self.course) so we can access student-specific data. + Bind a block (part of self.course) so we can access student-specific data. """ - module_system = get_test_system(course_id=module.location.course_key) - module_system.descriptor_runtime = module.runtime._descriptor_system # pylint: disable=protected-access + module_system = get_test_system(course_id=block.location.course_key) + module_system.descriptor_runtime = block.runtime._descriptor_system # pylint: disable=protected-access module_system._services['library_tools'] = LibraryToolsService(self.store, self.user.id) # pylint: disable=protected-access def get_block(descriptor): """Mocks module_system get_block_for_descriptor function""" - sub_module_system = get_test_system(course_id=module.location.course_key) + sub_module_system = get_test_system(course_id=block.location.course_key) sub_module_system.get_block_for_descriptor = get_block sub_module_system.descriptor_runtime = descriptor._runtime # pylint: disable=protected-access descriptor.bind_for_student(sub_module_system, self.user.id) return descriptor module_system.get_block_for_descriptor = get_block - module.xmodule_runtime = module_system + block.xmodule_runtime = module_system def test_completion_service(self): # Only the completions for the user and course specified for the CompletionService diff --git a/xmodule/capa/tests/helpers.py b/xmodule/capa/tests/helpers.py index ecb94d6283..c464e64e93 100644 --- a/xmodule/capa/tests/helpers.py +++ b/xmodule/capa/tests/helpers.py @@ -89,7 +89,7 @@ def mock_capa_block(): """ def mock_location_text(self): # lint-amnesty, pylint: disable=unused-argument """ - Mock implementation of __unicode__ or __str__ for the module's location. + Mock implementation of __unicode__ or __str__ for the block's location. """ return 'i4x://Foo/bar/mock/abc' diff --git a/xmodule/capa/util.py b/xmodule/capa/util.py index 163a1c86ea..66e7b12390 100644 --- a/xmodule/capa/util.py +++ b/xmodule/capa/util.py @@ -236,7 +236,7 @@ def get_course_id_from_capa_block(capa_block): capa_block (ProblemBlock|None) Returns: str|None - The stringified course run key of the module. + The stringified course run key of the block. If not available, fall back to None. """ if not capa_block: diff --git a/xmodule/conditional_block.py b/xmodule/conditional_block.py index 914b3919f0..8f9c53776c 100644 --- a/xmodule/conditional_block.py +++ b/xmodule/conditional_block.py @@ -60,18 +60,18 @@ class ConditionalBlock( tag attributes: - sources - location id of required modules, separated by ';' + sources - location id of required blocks, separated by ';' - submitted - map to `is_submitted` module method. + submitted - map to `is_submitted` block method. (pressing RESET button makes this function to return False.) - attempted - map to `is_attempted` module method - correct - map to `is_correct` module method - poll_answer - map to `poll_answer` module attribute - voted - map to `voted` module attribute + attempted - map to `is_attempted` block method + correct - map to `is_correct` block method + poll_answer - map to `poll_answer` block attribute + voted - map to `voted` block attribute tag attributes: - sources - location id of required modules, separated by ';' + sources - location id of required blocks, separated by ';' You can add you own rules for tag, like "completed", "attempted" etc. To do that yo must extend @@ -83,7 +83,7 @@ class ConditionalBlock( ... - And my_property/my_method will be called for required modules. + And my_property/my_method will be called for required blocks. """ @@ -170,7 +170,7 @@ class ConditionalBlock( # Map # key: - # value: + # value: conditions_map = { 'poll_answer': 'poll_answer', # poll_question attr @@ -210,20 +210,20 @@ class ConditionalBlock( attr_name = self.conditions_map[self.conditional_attr] if self.conditional_value and self.get_required_blocks: - for module in self.get_required_blocks: - if not hasattr(module, attr_name): + for block in self.get_required_blocks: + if not hasattr(block, attr_name): # We don't throw an exception here because it is possible for - # the descriptor of a required module to have a property but + # the descriptor of a required block to have a property but # for the resulting module to be a (flavor of) ErrorBlock. # So just log and return false. - if module is not None: - # We do not want to log when module is None, and it is when requester - # does not have access to the requested required module. + if block is not None: + # We do not want to log when block is None, and it is when requester + # does not have access to the requested required block. log.warning('Error in conditional block: \ - required module {module} has no {module_attr}'.format(module=module, module_attr=attr_name)) + required module {block} has no {block_attr}'.format(block=block, block_attr=attr_name)) return False - attr = getattr(module, attr_name) + attr = getattr(block, attr_name) if callable(attr): attr = attr() @@ -278,7 +278,7 @@ class ConditionalBlock( return fragment def handle_ajax(self, _dispatch, _data): - """This is called by courseware.moduleodule_render, to handle + """This is called by courseware.block_render, to handle an AJAX call. """ if not self.is_condition_satisfied(): @@ -318,10 +318,10 @@ class ConditionalBlock( Returns a list of bound XBlocks instances upon which XBlock depends. """ return [ - self.system.get_block_for_descriptor(descriptor) for descriptor in self.get_required_module_descriptors() + self.system.get_block_for_descriptor(descriptor) for descriptor in self.get_required_block_descriptors() ] - def get_required_module_descriptors(self): + def get_required_block_descriptors(self): """ Returns a list of unbound XBlocks instances upon which this XBlock depends. """ diff --git a/xmodule/course_block.py b/xmodule/course_block.py index 668ae59897..d6277784bf 100644 --- a/xmodule/course_block.py +++ b/xmodule/course_block.py @@ -314,7 +314,7 @@ class CourseFields: # lint-amnesty, pylint: disable=missing-class-docstring enrollment_start = Date(help=_("Date that enrollment for this class is opened"), scope=Scope.settings) enrollment_end = Date(help=_("Date that enrollment for this class is closed"), scope=Scope.settings) start = Date( - help=_("Start time when this module is visible"), + help=_("Start time when this block is visible"), default=DEFAULT_START_DATE, scope=Scope.settings ) @@ -795,7 +795,7 @@ class CourseFields: # lint-amnesty, pylint: disable=missing-class-docstring entrance_exam_id = String( display_name=_("Entrance Exam ID"), - help=_("Content module identifier (location) of entrance exam."), + help=_("Content block identifier (location) of entrance exam."), default=None, scope=Scope.settings, ) diff --git a/xmodule/error_block.py b/xmodule/error_block.py index 2a6fc7abe9..10a9300bdd 100644 --- a/xmodule/error_block.py +++ b/xmodule/error_block.py @@ -1,6 +1,6 @@ """ -Modules that get shown to the users when an error has occurred while -loading or rendering other modules +Block that get shown to the users when an error has occurred while +loading or rendering other blocks """ @@ -27,11 +27,11 @@ from xmodule.x_module import ( log = logging.getLogger(__name__) # NOTE: This is not the most beautiful design in the world, but there's no good -# way to tell if the module is being used in a staff context or not. Errors that get discovered +# way to tell if the block is being used in a staff context or not. Errors that get discovered # at course load time are turned into ErrorBlock objects, and automatically hidden from students. -# Unfortunately, we can also have errors when loading modules mid-request, and then we need to decide +# Unfortunately, we can also have errors when loading blocks mid-request, and then we need to decide # what to show, and the logic for that belongs in the LMS (e.g. in get_block), so the error handler -# decides whether to create a staff or not-staff module. +# decides whether to create a staff or not-staff block. class ErrorFields: @@ -52,8 +52,8 @@ class ErrorBlock( XModuleMixin, ): # pylint: disable=abstract-method """ - Module that gets shown to staff when there has been an error while - loading or rendering other modules + Block that gets shown to staff when there has been an error while + loading or rendering other blocks """ resources_dir = None @@ -99,7 +99,7 @@ class ErrorBlock( # Pick a unique url_name -- the sha1 hash of the contents. # NOTE: We could try to pull out the url_name of the errored descriptor, # but url_names aren't guaranteed to be unique between descriptor types, - # and ErrorBlock can wrap any type. When the wrapped module is fixed, + # and ErrorBlock can wrap any type. When the wrapped block is fixed, # it will be written out with the original url_name. name=hashlib.sha1(contents.encode('utf8')).hexdigest() ) diff --git a/xmodule/graders.py b/xmodule/graders.py index bd90dab394..a587204d68 100644 --- a/xmodule/graders.py +++ b/xmodule/graders.py @@ -29,10 +29,10 @@ class ScoreBase(metaclass=abc.ABCMeta): """ Fields common to all scores include: - :param graded: Whether or not this module is graded + :param graded: Whether or not this block is graded :type graded: bool - :param first_attempted: When the module was first attempted, or None + :param first_attempted: When the block was first attempted, or None :type first_attempted: datetime|None """ self.graded = graded diff --git a/xmodule/html_block.py b/xmodule/html_block.py index 2c3e24d37e..e6b42465d3 100644 --- a/xmodule/html_block.py +++ b/xmodule/html_block.py @@ -60,7 +60,7 @@ class HtmlBlockMixin( # lint-amnesty, pylint: disable=abstract-method # use display_name_with_default for those default=_("Text") ) - data = String(help=_("Html contents to display for this module"), default="", scope=Scope.content) + data = String(help=_("Html contents to display for this block"), default="", scope=Scope.content) source_code = String( help=_("Source code for LaTeX documents. This feature is not well-supported."), scope=Scope.settings @@ -389,7 +389,7 @@ class AboutFields: # lint-amnesty, pylint: disable=missing-class-docstring default="overview", ) data = String( - help=_("Html contents to display for this module"), + help=_("Html contents to display for this block"), default="", scope=Scope.content ) @@ -449,7 +449,7 @@ class CourseInfoFields: scope=Scope.content ) data = String( - help=_("Html contents to display for this module"), + help=_("Html contents to display for this block"), default="
    ", scope=Scope.content ) diff --git a/xmodule/library_root_xblock.py b/xmodule/library_root_xblock.py index 97ec88aed6..70fb993ba9 100644 --- a/xmodule/library_root_xblock.py +++ b/xmodule/library_root_xblock.py @@ -60,7 +60,7 @@ class LibraryRoot(XBlock): def render_children(self, context, fragment, can_reorder=False, can_add=False): # pylint: disable=unused-argument """ - Renders the children of the module with HTML appropriate for Studio. Reordering is not supported. + Renders the children of the block with HTML appropriate for Studio. Reordering is not supported. """ contents = [] diff --git a/xmodule/lti_2_util.py b/xmodule/lti_2_util.py index 93faa807c7..11eba5ee6d 100644 --- a/xmodule/lti_2_util.py +++ b/xmodule/lti_2_util.py @@ -220,7 +220,7 @@ class LTI20BlockMixin: self.clear_user_module_score(real_user) return Response(status=200) - # Fall-through record the score and the comment in the module + # Fall-through record the score and the comment in the block self.set_user_module_score(real_user, score, self.max_score(), comment) return Response(status=200) diff --git a/xmodule/mako_block.py b/xmodule/mako_block.py index 83572097fa..52415dfea8 100644 --- a/xmodule/mako_block.py +++ b/xmodule/mako_block.py @@ -32,7 +32,7 @@ class MakoDescriptorSystem(DescriptorSystem): # lint-amnesty, pylint: disable=a class MakoTemplateBlockBase: """ XBlock intended as a mixin that uses a mako template - to specify the module html. + to specify the block html. Expects the descriptor to have the `mako_template` attribute set with the name of the template to render, and it will pass diff --git a/xmodule/modulestore/__init__.py b/xmodule/modulestore/__init__.py index 4b2634484a..d02d62e142 100644 --- a/xmodule/modulestore/__init__.py +++ b/xmodule/modulestore/__init__.py @@ -784,7 +784,7 @@ class ModuleStoreRead(ModuleStoreAssetBase, metaclass=ABCMeta): usage_key: A :class:`.UsageKey` subclass instance depth (int): An argument that some module stores may use to prefetch - descendents of the queried modules for more efficient results later + descendents of the queried blocks for more efficient results later in the request. The depth is counted in the number of calls to get_children() to cache. None indicates to cache all descendents """ @@ -1283,7 +1283,7 @@ class ModuleStoreWriteBase(ModuleStoreReadBase, ModuleStoreWrite): 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. """ - # clone a default 'about' overview module as well + # clone a default 'about' overview block as well about_location = self.make_course_key(org, course, run).make_usage_key('about', 'overview') about_descriptor = XBlock.load_class('about') diff --git a/xmodule/modulestore/inheritance.py b/xmodule/modulestore/inheritance.py index 315ce6e509..e75b9ab083 100644 --- a/xmodule/modulestore/inheritance.py +++ b/xmodule/modulestore/inheritance.py @@ -32,12 +32,12 @@ class InheritanceMixin(XBlockMixin): """Field definitions for inheritable fields.""" graded = Boolean( - help="Whether this module contributes to the final course grade", + help="Whether this block contributes to the final course grade", scope=Scope.settings, default=False, ) start = Date( - help="Start time when this module is visible", + help="Start time when this block is visible", default=DEFAULT_START_DATE, scope=Scope.settings ) @@ -220,8 +220,8 @@ class InheritanceMixin(XBlockMixin): ) in_entrance_exam = Boolean( - display_name=_("Tag this module as part of an Entrance Exam section"), - help=_("Enter true or false. If true, answer submissions for problem modules will be " + display_name=_("Tag this block as part of an Entrance Exam section"), + help=_("Enter true or false. If true, answer submissions for problem blocks will be " "considered in the Entrance Exam scoring/gating algorithm."), scope=Scope.settings, default=False @@ -294,7 +294,7 @@ def compute_inherited_metadata(descriptor): def inherit_metadata(descriptor, inherited_data): """ - Updates this module with metadata inherited from a containing module. + Updates this block with metadata inherited from a containing block. Only metadata specified in self.inheritable_metadata will be inherited @@ -307,12 +307,12 @@ def inherit_metadata(descriptor, inherited_data): pass -def own_metadata(module): +def own_metadata(block): """ Return a JSON-friendly dictionary that contains only non-inherited field keys, mapped to their serialized values """ - return module.get_explicitly_set_fields_by_scope(Scope.settings) + return block.get_explicitly_set_fields_by_scope(Scope.settings) class InheritingFieldData(KvsFieldData): diff --git a/xmodule/modulestore/mixed.py b/xmodule/modulestore/mixed.py index 57a36b204d..58c58e32f3 100644 --- a/xmodule/modulestore/mixed.py +++ b/xmodule/modulestore/mixed.py @@ -852,7 +852,7 @@ class MixedModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase): @strip_key def create_xblock(self, runtime, course_key, block_type, block_id=None, fields=None, **kwargs): """ - Create the new xmodule but don't save it. Returns the new module. + Create the new xblock but don't save it. Returns the new block. Args: runtime: :py:class `xblock.runtime` from another xblock in the same course. Providing this diff --git a/xmodule/modulestore/mongo/base.py b/xmodule/modulestore/mongo/base.py index 93e09dda3c..39532a8201 100644 --- a/xmodule/modulestore/mongo/base.py +++ b/xmodule/modulestore/mongo/base.py @@ -167,7 +167,7 @@ class MongoKeyValueStore(InheritanceKeyValueStore): 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 + A system that has a cache of block json that it will use to load blocks from, with a backup of calling to the underlying modulestore for more data """ def __repr__(self): @@ -180,7 +180,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li def __init__(self, modulestore, course_key, module_data, default_class, **kwargs): """ - modulestore: the module store that can be used to retrieve additional modules + modulestore: the module store that can be used to retrieve additional blocks course_key: the course for which everything in this runtime will be relative @@ -214,7 +214,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li def load_item(self, location, for_parent=None): # lint-amnesty, pylint: disable=method-hidden """ - Return an XModule instance for the specified location + Return an XBlock instance for the specified location """ assert isinstance(location, UsageKey) @@ -227,10 +227,10 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li json_data = self.module_data.get(location) if json_data is None: - module = self.modulestore.get_item(location, using_descriptor_system=self) - return module + block = self.modulestore.get_item(location, using_descriptor_system=self) + return block else: - # load the module and apply the inherited metadata + # load the block and apply the inherited metadata try: category = json_data['location']['category'] class_ = self.load_block_type(category) @@ -269,31 +269,31 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li field_data = KvsFieldData(kvs) scope_ids = ScopeIds(None, category, location, location) - module = self.construct_xblock_from_class(class_, scope_ids, field_data, for_parent=for_parent) + block = self.construct_xblock_from_class(class_, scope_ids, field_data, for_parent=for_parent) non_draft_loc = as_published(location) metadata_inheritance_tree = self.modulestore._compute_metadata_inheritance_tree(self.course_id) - inherit_metadata(module, metadata_inheritance_tree.get(str(non_draft_loc), {})) + inherit_metadata(block, metadata_inheritance_tree.get(str(non_draft_loc), {})) - module._edit_info = json_data.get('edit_info') + block._edit_info = json_data.get('edit_info') # migrate published_by and published_on if edit_info isn't present - if module._edit_info is None: - module._edit_info = {} + if block._edit_info is None: + block._edit_info = {} raw_metadata = json_data.get('metadata', {}) # published_on was previously stored as a list of time components instead of a datetime if raw_metadata.get('published_date'): - module._edit_info['published_date'] = datetime( + block._edit_info['published_date'] = datetime( *raw_metadata.get('published_date')[0:6] ).replace(tzinfo=UTC) - module._edit_info['published_by'] = raw_metadata.get('published_by') + block._edit_info['published_by'] = raw_metadata.get('published_by') for wrapper in self.modulestore.xblock_field_data_wrappers: - module._field_data = wrapper(module, module._field_data) # pylint: disable=protected-access + block._field_data = wrapper(block, block._field_data) # pylint: disable=protected-access # decache any computed pending field settings - module.save() - return module + block.save() + return block except Exception: # pylint: disable=broad-except log.warning("Failed to load descriptor from %s", json_data, exc_info=True) return ErrorBlock.from_json( @@ -835,7 +835,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo def _load_items(self, course_key, items, depth=0, using_descriptor_system=None, for_parent=None): """ - Load a list of xmodules from the data in items, with children cached up + Load a list of xblocks from the data in items, with children cached up to specified depth """ course_key = self.fill_in_run(course_key) @@ -1041,21 +1041,21 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo Arguments: usage_key: a :class:`.UsageKey` instance depth (int): An argument that some module stores may use to prefetch - descendents of the queried modules for more efficient results later + descendents of the queried blocks for more efficient results later in the request. The depth is counted in the number of calls to get_children() to cache. None indicates to cache all descendents. using_descriptor_system (CachingDescriptorSystem): The existing CachingDescriptorSystem to add data to, and to load the XBlocks from. """ item = self._find_one(usage_key) - module = self._load_items( + block = self._load_items( usage_key.course_key, [item], depth, using_descriptor_system=using_descriptor_system, for_parent=for_parent, )[0] - return module + return block @staticmethod def _course_key_to_son(course_id, tag='i4x'): @@ -1144,12 +1144,12 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo sort=[SORT_REVISION_FAVOR_DRAFT], ) - modules = self._load_items( + blocks = self._load_items( course_id, list(items), using_descriptor_system=using_descriptor_system ) - return modules + return blocks def create_course(self, org, course, run, user_id, fields=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ """ @@ -1199,10 +1199,10 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo metadata=None, definition_data=None, **kwargs ): """ - Create the new xblock but don't save it. Returns the new module. + Create the new xblock but don't save it. Returns the new block. :param runtime: if you already have an xblock from the course, the xblock.runtime value - :param fields: a dictionary of field names and values for the new xmodule + :param fields: a dictionary of field names and values for the new xblock """ if metadata is None: metadata = {} @@ -1245,7 +1245,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo xblock_class = runtime.load_block_type(block_type) location = course_key.make_usage_key(block_type, block_id) dbmodel = self._create_new_field_data(block_type, location, definition_data, metadata) - xmodule = runtime.construct_xblock_from_class( + xblock = runtime.construct_xblock_from_class( xblock_class, # We're loading a descriptor, so student_id is meaningless # We also don't have separate notions of definition and usage ids yet, @@ -1256,10 +1256,10 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo ) if fields is not None: for key, value in fields.items(): - setattr(xmodule, key, value) + setattr(xblock, key, value) # decache any pending field settings from init - xmodule.save() - return xmodule + xblock.save() + return xblock def create_item(self, user_id, course_key, block_type, block_id=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ """ @@ -1268,7 +1268,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo Returns the newly created item. Args: - user_id: ID of the user creating and saving the xmodule + user_id: ID of the user creating and saving the xblock course_key: A :class:`~opaque_keys.edx.CourseKey` identifying which course to create this item in block_type: The typo of block to create @@ -1294,7 +1294,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo Returns the newly created item. Args: - user_id: ID of the user creating and saving the xmodule + user_id: ID of the user creating and saving the xblock parent_usage_key: a :class:`~opaque_key.edx.UsageKey` identifing the block that this item should be parented under block_type: The typo of block to create @@ -1332,8 +1332,8 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo def _get_course_for_item(self, location, depth=0): ''' - for a given Xmodule, return the course that it belongs to - Also we have to assert that this module maps to only one course item - it'll throw an + for a given XBlock, return the course that it belongs to + Also we have to assert that this block maps to only one course item - it'll throw an assert if not ''' return self.get_course(location.course_key, depth) @@ -1631,7 +1631,7 @@ class MongoModuleStore(ModuleStoreDraftAndPublished, ModuleStoreWriteBase, Mongo def _create_new_field_data(self, _category, _location, definition_data, metadata): """ - To instantiate a new xmodule which will be saved later, set up the dbModel and kvs + To instantiate a new xblock which will be saved later, set up the dbModel and kvs """ kvs = MongoKeyValueStore( definition_data, diff --git a/xmodule/modulestore/mongo/draft.py b/xmodule/modulestore/mongo/draft.py index 2caca673fb..60eebdd31b 100644 --- a/xmodule/modulestore/mongo/draft.py +++ b/xmodule/modulestore/mongo/draft.py @@ -1,6 +1,6 @@ """ -A ModuleStore that knows about a special version DRAFT. Modules -marked as DRAFT are read in preference to modules without the DRAFT +A ModuleStore that knows about a special version DRAFT. Blocks +marked as DRAFT are read in preference to blocks without the DRAFT version by this ModuleStore (so, access to i4x://org/course/cat/name returns the i4x://org/course/cat/name@draft object if that exists, and otherwise returns i4x://org/course/cat/name). @@ -55,8 +55,8 @@ class DraftModuleStore(MongoModuleStore): Reads are first read with revision DRAFT, and then fall back to the baseline revision only if DRAFT doesn't exist. - This module also includes functionality to promote DRAFT modules (and their children) - to published modules. + This module store also includes functionality to promote DRAFT blocks (and their children) + to published blocks. """ def get_item(self, usage_key, depth=0, revision=None, using_descriptor_system=None, **kwargs): # lint-amnesty, pylint: disable=arguments-differ """ @@ -66,7 +66,7 @@ class DraftModuleStore(MongoModuleStore): usage_key: A :class:`.UsageKey` instance depth (int): An argument that some module stores may use to prefetch - descendants of the queried modules for more efficient results later + descendants of the queried blocks for more efficient results later in the request. The depth is counted in the number of calls to get_children() to cache. None indicates to cache all descendants. @@ -219,42 +219,42 @@ class DraftModuleStore(MongoModuleStore): setattr(new_course, key, value) self.update_item(new_course, user_id) - # Get all modules under this namespace which is (tag, org, course) tuple - modules = self.get_items(source_course_id, revision=ModuleStoreEnum.RevisionOption.published_only) - self._clone_modules(modules, dest_course_id, user_id) + # Get all blocks under this namespace which is (tag, org, course) tuple + blocks = self.get_items(source_course_id, revision=ModuleStoreEnum.RevisionOption.published_only) + self._clone_blocks(blocks, dest_course_id, user_id) course_location = dest_course_id.make_usage_key('course', dest_course_id.run) self.publish(course_location, user_id) - modules = self.get_items(source_course_id, revision=ModuleStoreEnum.RevisionOption.draft_only) - self._clone_modules(modules, dest_course_id, user_id) + blocks = self.get_items(source_course_id, revision=ModuleStoreEnum.RevisionOption.draft_only) + self._clone_blocks(blocks, dest_course_id, user_id) return True - def _clone_modules(self, modules, dest_course_id, user_id): - """Clones each module into the given course""" - for module in modules: - original_loc = module.location - module.location = module.location.map_into_course(dest_course_id) - if module.location.block_type == 'course': - module.location = module.location.replace(name=module.location.run) + def _clone_blocks(self, blocks, dest_course_id, user_id): + """Clones each block into the given course""" + for block in blocks: + original_loc = block.location + block.location = block.location.map_into_course(dest_course_id) + if block.location.block_type == 'course': + block.location = block.location.replace(name=block.location.run) - log.info("Cloning module %s to %s....", original_loc, module.location) + log.info("Cloning block %s to %s....", original_loc, block.location) - if 'data' in module.fields and module.fields['data'].is_set_on(module) and isinstance(module.data, str): # lint-amnesty, pylint: disable=line-too-long - module.data = rewrite_nonportable_content_links( - original_loc.course_key, dest_course_id, module.data + if 'data' in block.fields and block.fields['data'].is_set_on(block) and isinstance(block.data, str): # lint-amnesty, pylint: disable=line-too-long + block.data = rewrite_nonportable_content_links( + original_loc.course_key, dest_course_id, block.data ) # repoint children - if module.has_children: + if block.has_children: new_children = [] - for child_loc in module.children: + for child_loc in block.children: child_loc = child_loc.map_into_course(dest_course_id) new_children.append(child_loc) - module.children = new_children + block.children = new_children - self.update_item(module, user_id, allow_not_found=True) + self.update_item(block, user_id, allow_not_found=True) def _get_raw_parent_locations(self, location, key_revision): """ @@ -321,8 +321,8 @@ class DraftModuleStore(MongoModuleStore): 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. + Create the new xblock but don't save it. Returns the new block with a draft locator if + the category allows drafts. If the category does not allow drafts, just creates a published block. :param location: a Location--must have a category :param definition_data: can be empty. The initial definition_data for the kvs @@ -596,16 +596,16 @@ class DraftModuleStore(MongoModuleStore): child_loc = UsageKey.from_string(child_loc).map_into_course(course_key) # single parent can have 2 versions: draft and published - # get draft parents only while deleting draft module + # get draft parents only while deleting draft block if draft_only: revision = MongoRevisionKey.draft else: revision = ModuleStoreEnum.RevisionOption.all parents = self._get_raw_parent_locations(child_loc, revision) - # Don't delete modules if one of its parents shouldn't be deleted + # Don't delete blocks if one of its parents shouldn't be deleted # This should only be an issue for courses have ended up in - # a state where modules have multiple parents + # a state where blocks have multiple parents if all(parent.to_deprecated_son() in to_be_deleted for parent in parents): for rev_func in as_functions: current_loc = rev_func(child_loc) diff --git a/xmodule/modulestore/search.py b/xmodule/modulestore/search.py index 136568eada..6031703982 100644 --- a/xmodule/modulestore/search.py +++ b/xmodule/modulestore/search.py @@ -16,7 +16,7 @@ def path_to_location(modulestore, usage_key, request=None, full_path=False): ''' Try to find a course_id/chapter/section[/position] path to location in modulestore. The courseware insists that the first level in the course is - chapter, but any kind of module can be a "section". + chapter, but any kind of block can be a "section". Args: modulestore: which store holds the relevant objects @@ -101,12 +101,12 @@ def path_to_location(modulestore, usage_key, request=None, full_path=False): # Figure out the position position = None - # This block of code will find the position of a module within a nested tree - # of modules. If a problem is on tab 2 of a sequence that's on tab 3 of a - # sequence, the resulting position is 3_2. However, no positional modules + # This block of code will find the position of a block within a nested tree + # of blocks. If a problem is on tab 2 of a sequence that's on tab 3 of a + # sequence, the resulting position is 3_2. However, no positional blocks # (e.g. sequential) currently deal with this form of representing nested - # positions. This needs to happen before jumping to a module nested in more - # than one positional module will work. + # positions. This needs to happen before jumping to a block nested in more + # than one positional block will work. if n > 3: position_list = [] diff --git a/xmodule/modulestore/split_mongo/caching_descriptor_system.py b/xmodule/modulestore/split_mongo/caching_descriptor_system.py index 55aa112f5b..5cb0bb3571 100644 --- a/xmodule/modulestore/split_mongo/caching_descriptor_system.py +++ b/xmodule/modulestore/split_mongo/caching_descriptor_system.py @@ -28,7 +28,7 @@ log = logging.getLogger(__name__) 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 + A system that has a cache of a course version's json that it will use to load blocks from, with a backup of calling to the underlying modulestore for more data. Computes the settings (nee 'metadata') inheritance upon creation. @@ -37,8 +37,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li """ Computes the settings inheritance and sets up the cache. - modulestore: the module store that can be used to retrieve additional - modules + modulestore: the module store that can be used to retrieve additional blocks course_entry: the originally fetched enveloped course_structure w/ branch and course id info. Callers to _load_item provide an override but that function ignores the provided structure and @@ -112,9 +111,9 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li version_guid = course_key.version_guid # look in cache - cached_module = self.modulestore.get_cached_block(course_key, version_guid, block_key) - if cached_module: - return cached_module + cached_block = self.modulestore.get_cached_block(course_key, version_guid, block_key) + if cached_block: + return cached_block block_data = self.get_module_data(block_key, course_key) @@ -234,7 +233,7 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li else: field_data = KvsFieldData(kvs) - module = self.construct_xblock_from_class( + block = self.construct_xblock_from_class( class_, ScopeIds(None, block_key.type, definition_id, block_locator), field_data, @@ -253,24 +252,24 @@ class CachingDescriptorSystem(MakoDescriptorSystem, EditInfoRuntimeMixin): # li ) edit_info = block_data.edit_info - module._edited_by = edit_info.edited_by # pylint: disable=protected-access - module._edited_on = edit_info.edited_on # pylint: disable=protected-access - module.previous_version = edit_info.previous_version - module.update_version = edit_info.update_version - module.source_version = edit_info.source_version - module.definition_locator = DefinitionLocator(block_key.type, definition_id) + block._edited_by = edit_info.edited_by # pylint: disable=protected-access + block._edited_on = edit_info.edited_on # pylint: disable=protected-access + block.previous_version = edit_info.previous_version + block.update_version = edit_info.update_version + block.source_version = edit_info.source_version + block.definition_locator = DefinitionLocator(block_key.type, definition_id) for wrapper in self.modulestore.xblock_field_data_wrappers: - module._field_data = wrapper(module, module._field_data) # pylint: disable=protected-access + block._field_data = wrapper(block, block._field_data) # pylint: disable=protected-access # decache any pending field settings - module.save() + block.save() # If this is an in-memory block, store it in this system if isinstance(block_locator.block_id, LocalId): - self.local_modules[block_locator] = module + self.local_modules[block_locator] = block - return module + return block def get_edited_by(self, xblock): """ diff --git a/xmodule/modulestore/split_mongo/split.py b/xmodule/modulestore/split_mongo/split.py index 4f814986c0..9a10b931d5 100644 --- a/xmodule/modulestore/split_mongo/split.py +++ b/xmodule/modulestore/split_mongo/split.py @@ -1,5 +1,5 @@ """ -Provides full versioning CRUD and representation for collections of xblocks (e.g., courses, modules, etc). +Provides full versioning CRUD and representation for collections of xblocks (e.g., courses, blocks, etc). Representation: * course_index: a dictionary: @@ -140,7 +140,7 @@ class SplitBulkWriteRecord(BulkOpsRecord): # lint-amnesty, pylint: disable=miss self.index = None self.structures = {} self.structures_in_db = set() - # dict(version_guid, dict(BlockKey, module)) + # dict(version_guid, dict(BlockKey, block)) self.modules = defaultdict(dict) self.definitions = {} self.definitions_in_db = set() @@ -363,7 +363,7 @@ class SplitBulkWriteMixin(BulkOperationsMixin): def get_cached_block(self, course_key, version_guid, block_id): """ - If there's an active bulk_operation, see if it's cached this module and just return it + If there's an active bulk_operation, see if it's cached this block and just return it Don't do any extra work to get the ones which are not cached. Make the caller do the work & cache them. """ bulk_write_record = self._get_bulk_ops_record(course_key) @@ -723,13 +723,13 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase): lazy: whether to load definitions now or later """ with self.bulk_operations(course_key, emit_signals=False): - new_module_data = {} + new_block_data = {} for block_id in base_block_ids: - new_module_data = self.descendants( + new_block_data = self.descendants( system.course_entry.structure['blocks'], block_id, depth, - new_module_data + new_block_data ) # This method supports lazy loading, where the descendent definitions aren't loaded @@ -740,21 +740,21 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase): course_key, [ block.definition - for block in new_module_data.values() + for block in new_block_data.values() ] ) # Turn definitions into a map. definitions = {definition['_id']: definition for definition in descendent_definitions} - for block in new_module_data.values(): + for block in new_block_data.values(): if block.definition in definitions: definition = definitions[block.definition] # convert_fields gets done later in the runtime's xblock_from_json block.fields.update(definition.get('fields')) block.definition_loaded = True - system.module_data.update(new_module_data) + system.module_data.update(new_block_data) return system.module_data def _load_items(self, course_entry, block_keys, depth=0, **kwargs): @@ -1168,7 +1168,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase): 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 + descendants of the queried blocks for more efficient results later in the request. The depth is counted in the number of calls to get_children() to cache. None indicates to cache all descendants. @@ -1311,8 +1311,8 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase): :param block_key: BlockKey of the component whose path is to be checked :param course: actual db json of course from structures - :param path_cache: a dictionary that records which modules have a path to the root so that we don't have to - double count modules if we're computing this for a list of modules in a course. + :param path_cache: a dictionary that records which blocks have a path to the root so that we don't have to + double count blocks if we're computing this for a list of blocks in a course. :param parents_cache: a dictionary containing mapping of block_key to list of its parents. Optionally, this should be built for course structure to make this method faster. @@ -1700,7 +1700,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase): Returns the newly created item. Args: - user_id: ID of the user creating and saving the xmodule + user_id: ID of the user creating and saving the xblock parent_usage_key: a :class:`~opaque_key.edx.UsageKey` identifying the block that this item should be parented under block_type: The typo of block to create @@ -2080,7 +2080,7 @@ class SplitMongoModuleStore(SplitBulkWriteMixin, ModuleStoreWriteBase): parent_xblock is used to compute inherited metadata as well as to append the new xblock. json_data: - - 'block_type': the xmodule block_type + - 'block_type': the xblock block_type - 'fields': a dict of locally set fields (not inherited) in json format not pythonic typed format! - 'definition': the object id of the existing definition """ diff --git a/xmodule/modulestore/store_utilities.py b/xmodule/modulestore/store_utilities.py index da71999c01..45082ff43e 100644 --- a/xmodule/modulestore/store_utilities.py +++ b/xmodule/modulestore/store_utilities.py @@ -79,12 +79,12 @@ def rewrite_nonportable_content_links(source_course_id, dest_course_id, text): return text -def draft_node_constructor(module, url, parent_url, location=None, parent_location=None, index=None): +def draft_node_constructor(block, url, parent_url, location=None, parent_location=None, index=None): """ Contructs a draft_node namedtuple with defaults. """ draft_node = namedtuple('draft_node', ['module', 'location', 'url', 'parent_location', 'parent_url', 'index']) - return draft_node(module, location, url, parent_location, parent_url, index) + return draft_node(block, location, url, parent_location, parent_url, index) def get_draft_subtree_roots(draft_nodes): diff --git a/xmodule/modulestore/tests/factories.py b/xmodule/modulestore/tests/factories.py index bc6bf6ad96..b740b10e05 100644 --- a/xmodule/modulestore/tests/factories.py +++ b/xmodule/modulestore/tests/factories.py @@ -330,7 +330,7 @@ class BlockFactory(XModuleFactory): """ Uses ``**kwargs``: - :parent_location: (required): the location of the parent module + :parent_location: (required): the location of the parent block (e.g. the parent course or section) :category: the category of the resulting item. @@ -400,7 +400,7 @@ class BlockFactory(XModuleFactory): if display_name is not None: metadata['display_name'] = display_name - module = store.create_child( + block = store.create_child( user_id, parent.location, location.block_type, @@ -412,12 +412,12 @@ class BlockFactory(XModuleFactory): ) if has_score: - module.has_score = has_score + block.has_score = has_score if submission_start: - module.submission_start = submission_start + block.submission_start = submission_start if submission_end: - module.submission_end = submission_end - store.update_item(module, user_id) + block.submission_end = submission_end + store.update_item(block, user_id) # VS[compat] cdodge: This is a hack because static_tabs also have references from the course block, so # if we add one then we need to also add it to the policy information (i.e. metadata) @@ -430,19 +430,19 @@ class BlockFactory(XModuleFactory): store.update_item(course, user_id) # parent and publish the item, so it can be accessed - if 'detached' not in module._class_tags: # lint-amnesty, pylint: disable=protected-access + if 'detached' not in block._class_tags: # lint-amnesty, pylint: disable=protected-access parent.children.append(location) store.update_item(parent, user_id) if publish_item: published_parent = store.publish(parent.location, user_id) - # module is last child of parent + # block is last child of parent return published_parent.get_children()[-1] else: return store.get_item(location) elif publish_item: return store.publish(location, user_id) else: - return module + return block @contextmanager diff --git a/xmodule/modulestore/tests/test_mixed_modulestore.py b/xmodule/modulestore/tests/test_mixed_modulestore.py index 21c25347ba..a574a256cf 100644 --- a/xmodule/modulestore/tests/test_mixed_modulestore.py +++ b/xmodule/modulestore/tests/test_mixed_modulestore.py @@ -418,8 +418,8 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup): course_locn = self.course_locations[self.MONGO_COURSEID] with check_mongo_calls(max_find, max_send), self.assertNumQueries(num_mysql): - modules = self.store.get_items(course_locn.course_key, qualifiers={'category': 'problem'}) - assert len(modules) == 6 + blocks = self.store.get_items(course_locn.course_key, qualifiers={'category': 'problem'}) + assert len(blocks) == 6 # verify that an error is raised when the revision is not valid with pytest.raises(UnsupportedRevisionError): @@ -2676,7 +2676,7 @@ class TestMixedModuleStore(CommonMixedModuleStoreSetup): # Note: The signal is fired once when the course is created and # a second time after the actual data import. import_course_from_xml( - self.store, self.user_id, DATA_DIR, ['toy'], load_error_modules=False, + self.store, self.user_id, DATA_DIR, ['toy'], load_error_blocks=False, static_content_store=contentstore, create_if_not_present=True, ) @@ -3345,7 +3345,7 @@ class TestPublishOverExportImport(CommonMixedModuleStoreSetup): dest_course_key = self.store.make_course_key('edX', "aside_test", "2012_Fall") courses = import_course_from_xml( self.store, self.user_id, DATA_DIR, ['aside'], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore, target_id=dest_course_key, create_if_not_present=True, @@ -3421,7 +3421,7 @@ class TestPublishOverExportImport(CommonMixedModuleStoreSetup): self.user_id, DATA_DIR, ['aside'], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore, target_id=dest_course_key, create_if_not_present=True, @@ -3508,7 +3508,7 @@ class TestPublishOverExportImport(CommonMixedModuleStoreSetup): self.user_id, DATA_DIR, ['aside'], - load_error_modules=False, + load_error_blocks=False, static_content_store=contentstore, target_id=dest_course_key, create_if_not_present=True, diff --git a/xmodule/modulestore/tests/test_split_modulestore.py b/xmodule/modulestore/tests/test_split_modulestore.py index 56525f907b..13d128382b 100644 --- a/xmodule/modulestore/tests/test_split_modulestore.py +++ b/xmodule/modulestore/tests/test_split_modulestore.py @@ -1013,7 +1013,7 @@ class SplitModuleItemTests(SplitModuleTest): get_items(locator, qualifiers, [branch]) ''' locator = CourseLocator(org='testx', course='GreekHero', run="run", branch=BRANCH_NAME_DRAFT) - # get all modules + # get all blocks matches = modulestore().get_items(locator) assert len(matches) == 8 matches = modulestore().get_items(locator) @@ -1120,28 +1120,28 @@ class TestItemCrud(SplitModuleTest): premod_history = modulestore().get_course_history_info(locator) # add minimal one w/o a parent category = 'sequential' - new_module = modulestore().create_item( + new_block = modulestore().create_item( 'user123', locator, category, fields={'display_name': 'new sequential'} ) # check that course version changed and course's previous is the other one - assert new_module.location.course == 'GreekHero' - assert new_module.location.version_guid != premod_course.location.version_guid + assert new_block.location.course == 'GreekHero' + assert new_block.location.version_guid != premod_course.location.version_guid assert locator.version_guid is None,\ 'Version inadvertently filled in' # lint-amnesty, pylint: disable=no-member current_course = modulestore().get_course(locator) - assert new_module.location.version_guid == current_course.location.version_guid + assert new_block.location.version_guid == current_course.location.version_guid history_info = modulestore().get_course_history_info(current_course.location.course_key) assert history_info['previous_version'] == premod_course.location.version_guid assert history_info['original_version'] == premod_history['original_version'] assert history_info['edited_by'] == 'user123' # check block's info: category, definition_locator, and display_name - assert new_module.category == 'sequential' - assert new_module.definition_locator is not None - assert new_module.display_name == 'new sequential' + assert new_block.category == 'sequential' + assert new_block.definition_locator is not None + assert new_block.display_name == 'new sequential' # check that block does not exist in previous version - locator = new_module.location.map_into_course( + locator = new_block.location.map_into_course( CourseLocator(version_guid=premod_course.location.version_guid) ) with pytest.raises(ItemNotFoundError): @@ -1162,20 +1162,20 @@ class TestItemCrud(SplitModuleTest): ) premod_course = modulestore().get_course(locator.course_key) category = 'chapter' - new_module = modulestore().create_child( + new_block = modulestore().create_child( 'user123', locator, category, fields={'display_name': 'new chapter'}, definition_locator=original.definition_locator ) # check that course version changed and course's previous is the other one - assert new_module.location.version_guid != premod_course.location.version_guid + assert new_block.location.version_guid != premod_course.location.version_guid parent = modulestore().get_item(locator) - assert new_module.location.version_agnostic() in version_agnostic(parent.children) - assert new_module.definition_locator.definition_id == original.definition_locator.definition_id + assert new_block.location.version_agnostic() in version_agnostic(parent.children) + assert new_block.definition_locator.definition_id == original.definition_locator.definition_id def test_unique_naming(self): """ - Check that 2 modules of same type get unique block_ids. Also check that if creation provides + Check that 2 blocks of same type get unique block_ids. Also check that if creation provides a definition id and new def data that it branches the definition in the db. Actually, this tries to test all create_item features not tested above. """ @@ -1190,29 +1190,29 @@ class TestItemCrud(SplitModuleTest): ) category = 'problem' new_payload = "empty" - new_module = modulestore().create_child( + new_block = modulestore().create_child( 'anotheruser', locator, category, fields={'display_name': 'problem 1', 'data': new_payload}, ) another_payload = "not empty" - another_module = modulestore().create_child( + another_block = modulestore().create_child( 'anotheruser', locator, category, fields={'display_name': 'problem 2', 'data': another_payload}, definition_locator=original.definition_locator, ) # check that course version changed and course's previous is the other one parent = modulestore().get_item(locator) - assert new_module.location.block_id != another_module.location.block_id - assert new_module.location.version_agnostic() in version_agnostic(parent.children) - assert another_module.location.version_agnostic() in version_agnostic(parent.children) - assert new_module.data == new_payload - assert another_module.data == another_payload + assert new_block.location.block_id != another_block.location.block_id + assert new_block.location.version_agnostic() in version_agnostic(parent.children) + assert another_block.location.version_agnostic() in version_agnostic(parent.children) + assert new_block.data == new_payload + assert another_block.data == another_payload # check definition histories - new_history = modulestore().get_definition_history_info(new_module.definition_locator) + new_history = modulestore().get_definition_history_info(new_block.definition_locator) assert new_history['previous_version'] is None - assert new_history['original_version'] == new_module.definition_locator.definition_id + assert new_history['original_version'] == new_block.definition_locator.definition_id assert new_history['edited_by'] == 'anotheruser' - another_history = modulestore().get_definition_history_info(another_module.definition_locator) + another_history = modulestore().get_definition_history_info(another_block.definition_locator) assert another_history['previous_version'] == original.definition_locator.definition_id def test_encoded_naming(self): @@ -1228,8 +1228,8 @@ class TestItemCrud(SplitModuleTest): fields={'display_name': 'chapter 99'}, ) # check that course version changed and course's previous is the other one - new_module = modulestore().get_item(chapter_locator) - assert new_module.location.block_id == 'foo.bar_-~:0' + new_block = modulestore().get_item(chapter_locator) + assert new_block.location.block_id == 'foo.bar_-~:0' # hardcode to ensure BUL init didn't change # now try making that a parent of something new_payload = "empty" @@ -1240,8 +1240,8 @@ class TestItemCrud(SplitModuleTest): fields={'display_name': 'chapter 99', 'data': new_payload}, ) # check that course version changed and course's previous is the other one - new_module = modulestore().get_item(problem_locator) - assert new_module.location.block_id == problem_locator.block_id + new_block = modulestore().get_item(problem_locator) + assert new_block.location.block_id == problem_locator.block_id chapter = modulestore().get_item(chapter_locator) assert problem_locator in version_agnostic(chapter.children) @@ -1871,7 +1871,7 @@ class TestPublish(SplitModuleTest): ] self._check_course(source_course, dest_course, expected, unexpected) # add a child under chapter1 - new_module = modulestore().create_child( + new_block = modulestore().create_child( self.user_id, chapter1, "sequential", fields={'display_name': 'new sequential'}, ) @@ -1879,22 +1879,22 @@ class TestPublish(SplitModuleTest): expected.remove(BlockKey.from_usage_key(chapter1)) # check that it's not in published course with pytest.raises(ItemNotFoundError): - modulestore().get_item(new_module.location.map_into_course(dest_course)) + modulestore().get_item(new_block.location.map_into_course(dest_course)) # publish it - modulestore().copy(self.user_id, source_course, dest_course, [new_module.location], None) - expected.append(BlockKey.from_usage_key(new_module.location)) + modulestore().copy(self.user_id, source_course, dest_course, [new_block.location], None) + expected.append(BlockKey.from_usage_key(new_block.location)) # check that it is in the published course and that its parent is the chapter - pub_module = modulestore().get_item(new_module.location.map_into_course(dest_course)) - assert modulestore().get_parent_location(pub_module.location).block_id == chapter1.block_id + pub_block = modulestore().get_item(new_block.location.map_into_course(dest_course)) + assert modulestore().get_parent_location(pub_block.location).block_id == chapter1.block_id # ensure intentionally orphaned blocks work (e.g., course_info) - new_module = modulestore().create_item( + new_block = modulestore().create_item( self.user_id, source_course, "course_info", block_id="handouts" ) # publish it - modulestore().copy(self.user_id, source_course, dest_course, [new_module.location], None) - expected.append(BlockKey.from_usage_key(new_module.location)) + modulestore().copy(self.user_id, source_course, dest_course, [new_block.location], None) + expected.append(BlockKey.from_usage_key(new_block.location)) # check that it is in the published course (no error means it worked) - pub_module = modulestore().get_item(new_module.location.map_into_course(dest_course)) + pub_block = modulestore().get_item(new_block.location.map_into_course(dest_course)) self._check_course(source_course, dest_course, expected, unexpected) def test_exceptions(self): diff --git a/xmodule/modulestore/tests/test_store_utilities.py b/xmodule/modulestore/tests/test_store_utilities.py index fdc76655f7..1c1c86f4fc 100644 --- a/xmodule/modulestore/tests/test_store_utilities.py +++ b/xmodule/modulestore/tests/test_store_utilities.py @@ -76,9 +76,9 @@ class TestUtils(unittest.TestCase): @ddt.unpack def test_get_draft_subtree_roots(self, node_arguments_list, expected_roots_urls): """tests for get_draft_subtree_roots""" - module_nodes = [] + block_nodes = [] for node_args in node_arguments_list: - module_nodes.append(draft_node_constructor(Mock(), node_args[0], node_args[1])) - subtree_roots_urls = [root.url for root in get_draft_subtree_roots(module_nodes)] + block_nodes.append(draft_node_constructor(Mock(), node_args[0], node_args[1])) + subtree_roots_urls = [root.url for root in get_draft_subtree_roots(block_nodes)] # check that we return the expected urls assert set(subtree_roots_urls) == set(expected_roots_urls) diff --git a/xmodule/modulestore/tests/test_xml.py b/xmodule/modulestore/tests/test_xml.py index b2c10157fc..b22e3938b2 100644 --- a/xmodule/modulestore/tests/test_xml.py +++ b/xmodule/modulestore/tests/test_xml.py @@ -54,7 +54,7 @@ class TestXMLModuleStore(TestCase): DATA_DIR, source_dirs=['toy'], xblock_mixins=(XModuleMixin,), - load_error_modules=False) + load_error_blocks=False) # Look up the errors during load. There should be none. errors = modulestore.get_course_errors(CourseKey.from_string("edX/toy/2012_Fall")) @@ -152,10 +152,10 @@ class TestModuleStoreIgnore(TestXMLModuleStore): # lint-amnesty, pylint: disabl @patch("xmodule.modulestore.xml.glob.glob", side_effect=glob_tildes_at_end) def test_tilde_files_ignored(self, _fake_glob): - modulestore = XMLModuleStore(DATA_DIR, source_dirs=['course_ignore'], load_error_modules=False) + modulestore = XMLModuleStore(DATA_DIR, source_dirs=['course_ignore'], load_error_blocks=False) about_location = CourseKey.from_string('edX/course_ignore/2014_Fall').make_usage_key( 'about', 'index', ) - about_module = modulestore.get_item(about_location) - assert 'GREEN' in about_module.data - assert 'RED' not in about_module.data + about_block = modulestore.get_item(about_location) + assert 'GREEN' in about_block.data + assert 'RED' not in about_block.data diff --git a/xmodule/modulestore/tests/test_xml_importer.py b/xmodule/modulestore/tests/test_xml_importer.py index 6e0e69dc86..c59050b319 100644 --- a/xmodule/modulestore/tests/test_xml_importer.py +++ b/xmodule/modulestore/tests/test_xml_importer.py @@ -19,7 +19,7 @@ from xblock.runtime import DictKeyValueStore, KvsFieldData, Runtime from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.inheritance import InheritanceMixin from xmodule.modulestore.tests.mongo_connection import MONGO_HOST, MONGO_PORT_NUM -from xmodule.modulestore.xml_importer import StaticContentImporter, _update_and_import_module, _update_module_location +from xmodule.modulestore.xml_importer import StaticContentImporter, _update_and_import_block, _update_block_location from xmodule.tests import DATA_DIR from xmodule.x_module import XModuleMixin @@ -152,7 +152,7 @@ class RemapNamespaceTest(ModuleStoreNoSettings): # Move to different runtime w/ different course id target_location_namespace = CourseKey.from_string("org/course/run") - new_version = _update_and_import_module( + new_version = _update_and_import_block( self.xblock, modulestore(), 999, @@ -183,7 +183,7 @@ class RemapNamespaceTest(ModuleStoreNoSettings): # Remap the namespace target_location_namespace = BlockUsageLocator(CourseLocator("org", "course", "run"), "category", "stubxblock") - new_version = _update_and_import_module( + new_version = _update_and_import_block( self.xblock, modulestore(), 999, @@ -209,7 +209,7 @@ class RemapNamespaceTest(ModuleStoreNoSettings): # Remap the namespace target_location_namespace = BlockUsageLocator(CourseLocator("org", "course", "run"), "category", "stubxblock") - new_version = _update_and_import_module( + new_version = _update_and_import_block( self.xblock, modulestore(), 999, @@ -303,8 +303,8 @@ class UpdateLocationTest(ModuleStoreNoSettings): # Update location target_location = self.xblock.location.replace(revision='draft') - _update_module_location(self.xblock, target_location) - new_version = self.xblock # _update_module_location updates in-place + _update_block_location(self.xblock, target_location) + new_version = self.xblock # _update_block_location updates in-place # Check the XBlock's location assert new_version.location == target_location diff --git a/xmodule/modulestore/xml.py b/xmodule/modulestore/xml.py index 35c5244c13..497bad1d11 100644 --- a/xmodule/modulestore/xml.py +++ b/xmodule/modulestore/xml.py @@ -49,12 +49,12 @@ log = logging.getLogger(__name__) class ImportSystem(XMLParsingSystem, MakoDescriptorSystem): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring def __init__(self, xmlstore, course_id, course_dir, # lint-amnesty, pylint: disable=too-many-statements error_tracker, - load_error_modules=True, target_course_id=None, **kwargs): + load_error_blocks=True, target_course_id=None, **kwargs): """ A class that handles loading from xml. Does some munging to ensure that all elements have unique slugs. - xmlstore: the XMLModuleStore to store the loaded modules in + xmlstore: the XMLModuleStore to store the loaded blocks in """ self.unnamed = defaultdict(int) # category -> num of new url_names for that category self.used_names = defaultdict(set) # category -> set of used url_names @@ -62,7 +62,7 @@ class ImportSystem(XMLParsingSystem, MakoDescriptorSystem): # lint-amnesty, pyl # Adding the course_id as passed in for later reference rather than # having to recombine the org/course/url_name self.course_id = course_id - self.load_error_modules = load_error_modules + self.load_error_blocks = load_error_blocks self.modulestore = xmlstore def process_xml(xml): # lint-amnesty, pylint: disable=too-many-statements @@ -107,7 +107,7 @@ class ImportSystem(XMLParsingSystem, MakoDescriptorSystem): # lint-amnesty, pyl and re.search('[0-9a-fA-F]{12}$', url_name)) def fallback_name(orig_name=None): - """Return the fallback name for this module. This is a function instead of a variable + """Return the fallback name for this block. This is a function instead of a variable because we want it to be lazy.""" if looks_like_fallback(orig_name): # We're about to re-hash, in case something changed, so get rid of the tag_ and hash @@ -125,17 +125,17 @@ class ImportSystem(XMLParsingSystem, MakoDescriptorSystem): # lint-amnesty, pyl if tag in need_uniq_names: error_tracker("PROBLEM: no name of any kind specified for {tag}. Student " - "state will not be properly tracked for this module. Problem xml:" + "state will not be properly tracked for this block. Problem xml:" " '{xml}...'".format(tag=tag, xml=xml[:100])) else: # TODO (vshnayder): We may want to enable this once course repos are cleaned up. # (or we may want to give up on the requirement for non-state-relevant issues...) - # error_tracker("WARNING: no name specified for module. xml='{0}...'".format(xml[:100])) + # error_tracker("WARNING: no name specified for block. xml='{0}...'".format(xml[:100])) pass # Make sure everything is unique if url_name in self.used_names[tag]: - # Always complain about modules that store state. If it + # Always complain about blocks that store state. If it # doesn't store state, don't complain about things that are # hashed. if tag in need_uniq_names: @@ -166,7 +166,7 @@ class ImportSystem(XMLParsingSystem, MakoDescriptorSystem): # lint-amnesty, pyl id_manager, ) except Exception as err: # pylint: disable=broad-except - if not self.load_error_modules: + if not self.load_error_blocks: raise # Didn't load properly. Fall back on loading as an error @@ -304,7 +304,7 @@ class XMLModuleStore(ModuleStoreReadBase): def __init__( self, data_dir, default_class=None, source_dirs=None, course_ids=None, - load_error_modules=True, i18n_service=None, fs_service=None, user_service=None, + load_error_blocks=True, i18n_service=None, fs_service=None, user_service=None, signal_handler=None, target_course_id=None, **kwargs # pylint: disable=unused-argument ): """ @@ -329,7 +329,7 @@ class XMLModuleStore(ModuleStoreReadBase): if course_ids is not None: course_ids = [CourseKey.from_string(course_id) for course_id in course_ids] - self.load_error_modules = load_error_modules + self.load_error_blocks = load_error_blocks if default_class is None: self.default_class = None @@ -486,7 +486,7 @@ class XMLModuleStore(ModuleStoreReadBase): # VS[compat] : 'name' is deprecated, but support it for now... if course_data.get('name'): url_name = BlockUsageLocator.clean(course_data.get('name')) - tracker("'name' is deprecated for module xml. Please use " + tracker("'name' is deprecated for block xml. Please use " "display_name and url_name.") else: url_name = None @@ -519,7 +519,7 @@ class XMLModuleStore(ModuleStoreReadBase): course_id=course_id, course_dir=course_dir, error_tracker=tracker, - load_error_modules=self.load_error_modules, + load_error_blocks=self.load_error_blocks, get_policy=get_policy, mixins=self.xblock_mixins, default_class=self.default_class, @@ -639,12 +639,12 @@ class XMLModuleStore(ModuleStoreReadBase): else: try: # get and update data field in xblock runtime - module = system.get_block(loc) + block = system.get_block(loc) for key, value in data_content.items(): - setattr(module, key, value) - module.save() + setattr(block, key, value) + block.save() except ItemNotFoundError: - module = None + block = None data_content['location'] = loc data_content['category'] = category else: @@ -653,15 +653,15 @@ class XMLModuleStore(ModuleStoreReadBase): # html file with html data content html = f.read() try: - module = system.get_block(loc) - module.data = html - module.save() + block = system.get_block(loc) + block.data = html + block.save() except ItemNotFoundError: - module = None + block = None data_content = {'data': html, 'location': loc, 'category': category} - if module is None: - module = system.construct_xblock( + if block is None: + block = system.construct_xblock( category, # We're loading a descriptor, so student_id is meaningless # We also don't have separate notions of definition and usage ids yet, @@ -675,12 +675,12 @@ class XMLModuleStore(ModuleStoreReadBase): if category == "static_tab": tab = CourseTabList.get_tab_by_slug(tab_list=course_descriptor.tabs, url_slug=slug) if tab: - module.display_name = tab.name - module.course_staff_only = tab.course_staff_only - module.data_dir = course_dir - module.save() + block.display_name = tab.name + block.course_staff_only = tab.course_staff_only + block.data_dir = course_dir + block.save() - self.modules[course_descriptor.id][module.scope_ids.usage_id] = module + self.modules[course_descriptor.id][block.scope_ids.usage_id] = block except Exception as exc: # pylint: disable=broad-except logging.exception("Failed to load %s. Skipping... \ Exception: %s", filepath, str(exc)) @@ -702,7 +702,7 @@ class XMLModuleStore(ModuleStoreReadBase): If no object is found at that location, raises xmodule.modulestore.exceptions.ItemNotFoundError - usage_key: a UsageKey that matches the module we are looking for. + usage_key: a UsageKey that matches the block we are looking for. """ try: return self.modules[usage_key.course_key][usage_key] @@ -743,24 +743,24 @@ class XMLModuleStore(ModuleStoreReadBase): category = qualifiers.pop('category', None) name = qualifiers.pop('name', None) - def _block_matches_all(mod_loc, module): - if category and mod_loc.category != category: + def _block_matches_all(block_loc, block): + if category and block_loc.category != category: return False if name: if isinstance(name, list): # Support for passing a list as the name qualifier - if mod_loc.name not in name: + if block_loc.name not in name: return False - elif mod_loc.name != name: + elif block_loc.name != name: return False return all( - self._block_matches(module, fields or {}) + self._block_matches(block, fields or {}) for fields in [settings, content, qualifiers] ) - for mod_loc, module in self.modules[course_id].items(): - if _block_matches_all(mod_loc, module): - items.append(module) + for block_loc, block in self.modules[course_id].items(): + if _block_matches_all(block_loc, block): + items.append(block) return items diff --git a/xmodule/modulestore/xml_exporter.py b/xmodule/modulestore/xml_exporter.py index 79002f7ede..144d46e935 100644 --- a/xmodule/modulestore/xml_exporter.py +++ b/xmodule/modulestore/xml_exporter.py @@ -34,24 +34,24 @@ def _export_drafts(modulestore, course_key, export_fs, xml_centric_course_key): # NOTE: we need to explicitly implement the logic for setting the vertical's parent # and index here since the XML modulestore cannot load draft modules with modulestore.branch_setting(ModuleStoreEnum.Branch.draft_preferred, course_key): - draft_modules = modulestore.get_items( + draft_blocks = modulestore.get_items( course_key, qualifiers={'category': {'$nin': DIRECT_ONLY_CATEGORIES}}, revision=ModuleStoreEnum.RevisionOption.draft_only ) - # Check to see if the returned draft modules have changes w.r.t. the published module. - # Only modules with changes will be exported into the /drafts directory. - draft_modules = [module for module in draft_modules if modulestore.has_changes(module)] - if draft_modules: + # Check to see if the returned draft blocks have changes w.r.t. the published block. + # Only blocks with changes will be exported into the /drafts directory. + draft_blocks = [block for block in draft_blocks if modulestore.has_changes(block)] + if draft_blocks: draft_course_dir = export_fs.makedir(DRAFT_DIR, recreate=True) - # accumulate tuples of draft_modules and their parents in + # accumulate tuples of draft_blocks and their parents in # this list: draft_node_list = [] - for draft_module in draft_modules: + for draft_block in draft_blocks: parent_loc = modulestore.get_parent_location( - draft_module.location, + draft_block.location, revision=ModuleStoreEnum.RevisionOption.draft_preferred ) @@ -61,9 +61,9 @@ def _export_drafts(modulestore, course_key, export_fs, xml_centric_course_key): parent_url = str(parent_loc) draft_node = draft_node_constructor( - draft_module, - location=draft_module.location, - url=str(draft_module.location), + draft_block, + location=draft_block.location, + url=str(draft_block.location), parent_location=parent_loc, parent_url=parent_url, ) @@ -117,9 +117,9 @@ class ExportManager: """ def __init__(self, modulestore, contentstore, courselike_key, root_dir, target_dir): """ - Export all modules from `modulestore` and content from `contentstore` as xml to `root_dir`. + Export all blocks from `modulestore` and content from `contentstore` as xml to `root_dir`. - `modulestore`: A `ModuleStore` object that is the source of the modules to export + `modulestore`: A `ModuleStore` object that is the source of the blocks to export `contentstore`: A `ContentStore` object that is the source of the content to export, can be None `courselike_key`: The Locator of the Descriptor to export `root_dir`: The directory to write the exported xml to @@ -394,14 +394,14 @@ def _export_field_content(xblock_item, item_dir): """ Export all fields related to 'xblock_item' other than 'metadata' and 'data' to json file in provided directory """ - module_data = xblock_item.get_explicitly_set_fields_by_scope(Scope.content) - if isinstance(module_data, dict): - for field_name in module_data: + block_data = xblock_item.get_explicitly_set_fields_by_scope(Scope.content) + if isinstance(block_data, dict): + for field_name in block_data: if field_name not in DEFAULT_CONTENT_FIELDS: # filename format: {dirname}.{field_name}.json with item_dir.open('{}.{}.{}'.format(xblock_item.location.block_id, field_name, 'json'), 'wb') as field_content_file: - field_content_file.write(dumps(module_data.get(field_name, {}), cls=EdxJSONEncoder, + field_content_file.write(dumps(block_data.get(field_name, {}), cls=EdxJSONEncoder, sort_keys=True, indent=4).encode('utf-8')) diff --git a/xmodule/modulestore/xml_importer.py b/xmodule/modulestore/xml_importer.py index 89bb855067..2ab68f5d40 100644 --- a/xmodule/modulestore/xml_importer.py +++ b/xmodule/modulestore/xml_importer.py @@ -82,12 +82,12 @@ class ErrorReadingFileException(CourseImportException): super().__init__(**kwargs) -class ModuleFailedToImport(CourseImportException): +class BlockFailedToImport(CourseImportException): """ - Raised when a module is failed to import. + Raised when a block is failed to import. """ - MESSAGE_TEMPLATE = _('Failed to import module: {} at location: {}') + MESSAGE_TEMPLATE = _('Failed to import block: {} at location: {}') def __init__(self, display_name, location, **kwargs): self.description = self.MESSAGE_TEMPLATE.format(display_name, location) @@ -228,7 +228,7 @@ class ImportManager: source_dirs: If specified, the list of data_dir subdirectories to load. Otherwise, load all dirs - target_id: is the Locator that all modules should be remapped to + target_id: is the Locator that all blocks should be remapped to after import off disk. NOTE: this only makes sense if importing only one courselike. If there are more than one courselike loaded from data_dir/source_dirs & you supply this id, an AssertException will be raised. @@ -254,14 +254,14 @@ class ImportManager: python_lib_filename: The filename of the courselike's python library. Course authors can optionally create this file to implement custom logic in their course. - default_class, load_error_modules: are arguments for constructing the XMLModuleStore (see its doc) + default_class, load_error_blocks: are arguments for constructing the XMLModuleStore (see its doc) """ store_class = XMLModuleStore def __init__( self, store, user_id, data_dir, source_dirs=None, default_class='xmodule.hidden_block.HiddenBlock', - load_error_modules=True, static_content_store=None, + load_error_blocks=True, static_content_store=None, target_id=None, verbose=False, do_import_static=True, do_import_python_lib=True, create_if_not_present=False, raise_on_failure=False, @@ -272,7 +272,7 @@ class ImportManager: self.user_id = user_id self.data_dir = data_dir self.source_dirs = source_dirs - self.load_error_modules = load_error_modules + self.load_error_blocks = load_error_blocks self.static_content_store = static_content_store self.target_id = target_id self.verbose = verbose @@ -286,7 +286,7 @@ class ImportManager: data_dir, default_class=default_class, source_dirs=source_dirs, - load_error_modules=load_error_modules, + load_error_blocks=load_error_blocks, xblock_mixins=store.xblock_mixins, xblock_select=store.xblock_select, target_course_id=target_id, @@ -406,10 +406,10 @@ class ImportManager: def import_courselike(self, runtime, courselike_key, dest_id, source_courselike): """ - Import the base module/block + Import the base block """ if self.verbose: - log.debug("Scanning %s for courselike module...", courselike_key) + log.debug("Scanning %s for courselike block...", courselike_key) # Quick scan to get course block as we need some info from there. # Also we need to make sure that the course block is committed @@ -427,7 +427,7 @@ class ImportManager: log.debug('course data_dir=%s', source_courselike.data_dir) with self.store.branch_setting(ModuleStoreEnum.Branch.draft_preferred, dest_id): - course = _update_and_import_module( + course = _update_and_import_block( source_courselike, self.store, self.user_id, courselike_key, dest_id, @@ -497,10 +497,10 @@ class ImportManager: # ContentStoreTest.test_image_import pass if self.verbose: - log.debug('importing module location %s', child.location) + log.debug('importing block location %s', child.location) try: - _update_and_import_module( + _update_and_import_block( child, self.store, self.user_id, @@ -511,9 +511,9 @@ class ImportManager: ) except Exception: log.exception( - f'Course import {dest_id}: failed to import module location {child.location}' + f'Course import {dest_id}: failed to import block location {child.location}' ) - raise ModuleFailedToImport(child.display_name, child.location) # pylint: disable=raise-missing-from + raise BlockFailedToImport(child.display_name, child.location) # pylint: disable=raise-missing-from depth_first(child) @@ -521,10 +521,10 @@ class ImportManager: for leftover in all_locs: if self.verbose: - log.debug('importing module location %s', leftover) + log.debug('importing block location %s', leftover) try: - _update_and_import_module( + _update_and_import_block( self.xml_module_store.get_item(leftover), self.store, self.user_id, @@ -535,10 +535,10 @@ class ImportManager: ) except Exception: log.exception( - f'Course import {dest_id}: failed to import module location {leftover}' + f'Course import {dest_id}: failed to import block location {leftover}' ) # pylint: disable=raise-missing-from - raise ModuleFailedToImport(leftover.display_name, leftover.location) + raise BlockFailedToImport(leftover.display_name, leftover.location) def run_imports(self): """ @@ -783,19 +783,19 @@ def import_library_from_xml(*args, **kwargs): return list(manager.run_imports()) -def _update_and_import_module( - module, store, user_id, +def _update_and_import_block( + block, store, user_id, source_course_id, dest_course_id, do_import_static=True, runtime=None): """ - Update all the module reference fields to the destination course id, - then import the module into the destination course. + Update all the block reference fields to the destination course id, + then import the block into the destination course. """ - logging.debug('processing import of module %s...', str(module.location)) + logging.debug('processing import of blocks %s...', str(block.location)) - def _update_module_references(module, source_course_id, dest_course_id): + def _update_block_references(block, source_course_id, dest_course_id): """ - Move the module to a new course. + Move the block to a new course. """ def _convert_ref_fields_to_new_namespace(reference): @@ -812,26 +812,26 @@ def _update_and_import_module( return reference fields = {} - for field_name, field in module.fields.items(): - if field.scope != Scope.parent and field.is_set_on(module): + for field_name, field in block.fields.items(): + if field.scope != Scope.parent and field.is_set_on(block): if isinstance(field, Reference): - value = field.read_from(module) + value = field.read_from(block) if value is None: fields[field_name] = None else: - fields[field_name] = _convert_ref_fields_to_new_namespace(field.read_from(module)) + fields[field_name] = _convert_ref_fields_to_new_namespace(field.read_from(block)) elif isinstance(field, ReferenceList): - references = field.read_from(module) + references = field.read_from(block) fields[field_name] = [_convert_ref_fields_to_new_namespace(reference) for reference in references] elif isinstance(field, ReferenceValueDict): - reference_dict = field.read_from(module) + reference_dict = field.read_from(block) fields[field_name] = { key: _convert_ref_fields_to_new_namespace(reference) for key, reference in reference_dict.items() } elif field_name == 'xml_attributes': - value = field.read_from(module) + value = field.read_from(block) # remove any export/import only xml_attributes # which are used to wire together draft imports if 'parent_url' in value: @@ -843,28 +843,28 @@ def _update_and_import_module( del value['index_in_children_list'] fields[field_name] = value else: - fields[field_name] = field.read_from(module) + fields[field_name] = field.read_from(block) return fields - if do_import_static and 'data' in module.fields and isinstance(module.fields['data'], xblock.fields.String): + if do_import_static and 'data' in block.fields and isinstance(block.fields['data'], xblock.fields.String): # we want to convert all 'non-portable' links in the module_data # (if it is a string) to portable strings (e.g. /static/) - module.data = rewrite_nonportable_content_links( + block.data = rewrite_nonportable_content_links( source_course_id, dest_course_id, - module.data + block.data ) - fields = _update_module_references(module, source_course_id, dest_course_id) - asides = module.get_asides() if isinstance(module, XModuleMixin) else None + fields = _update_block_references(block, source_course_id, dest_course_id) + asides = block.get_asides() if isinstance(block, XModuleMixin) else None - if module.location.block_type == 'library_content': + if block.location.block_type == 'library_content': with store.branch_setting(branch_setting=ModuleStoreEnum.Branch.published_only): - lib_content_block_already_published = store.has_item(module.location) + lib_content_block_already_published = store.has_item(block.location) block = store.import_xblock( - user_id, dest_course_id, module.location.block_type, - module.location.block_id, fields, runtime, asides=asides + user_id, dest_course_id, block.location.block_type, + block.location.block_id, fields, runtime, asides=asides ) # TODO: Move this code once the following condition is met. @@ -952,25 +952,25 @@ def _import_course_draft( course_id=source_course_id, course_dir=draft_course_dir, error_tracker=errorlog.tracker, - load_error_modules=False, + load_error_blocks=False, mixins=xml_module_store.xblock_mixins, services={'field-data': KvsFieldData(kvs=DictKeyValueStore())}, target_course_id=target_id, ) - def _import_module(module): - # IMPORTANT: Be sure to update the module location in the NEW namespace - module_location = module.location.map_into_course(target_id) - # Update the module's location to DRAFT revision + def _import_block(block): + # IMPORTANT: Be sure to update the block location in the NEW namespace + block_location = block.location.map_into_course(target_id) + # Update the block's location to DRAFT revision # We need to call this method (instead of updating the location directly) # to ensure that pure XBlock field data is updated correctly. - _update_module_location(module, module_location.replace(revision=MongoRevisionKey.draft)) + _update_block_location(block, block_location.replace(revision=MongoRevisionKey.draft)) - parent_url = get_parent_url(module) - index = index_in_children_list(module) + parent_url = get_parent_url(block) + index = index_in_children_list(block) # make sure our parent has us in its list of children - # this is to make sure private only modules show up + # this is to make sure private only blocks show up # in the list of children since they would have been # filtered out from the non-draft store export. if parent_url is not None and index is not None: @@ -982,19 +982,19 @@ def _import_course_draft( parent = store.get_item(parent_location, depth=0) - non_draft_location = module.location.map_into_course(target_id) - if not any(child.block_id == module.location.block_id for child in parent.children): + non_draft_location = block.location.map_into_course(target_id) + if not any(child.block_id == block.location.block_id for child in parent.children): parent.children.insert(index, non_draft_location) store.update_item(parent, user_id) - _update_and_import_module( - module, store, user_id, + _update_and_import_block( + block, store, user_id, source_course_id, target_id, runtime=mongo_runtime, ) - for child in module.get_children(): - _import_module(child) + for child in block.get_children(): + _import_block(child) # Now walk the /drafts directory. # Each file in the directory will be a draft copy of the vertical. @@ -1007,8 +1007,8 @@ def _import_course_draft( if filename.startswith('._'): # Skip any OSX quarantine files, prefixed with a '._'. continue - module_path = os.path.join(rootdir, filename) - with open(module_path) as f: + block_path = os.path.join(rootdir, filename) + with open(block_path) as f: try: xml = f.read() @@ -1033,7 +1033,7 @@ def _import_course_draft( draft_url = str(descriptor.location) draft = draft_node_constructor( - module=descriptor, url=draft_url, parent_url=parent_url, index=index + block=descriptor, url=draft_url, parent_url=parent_url, index=index ) drafts.append(draft) @@ -1045,7 +1045,7 @@ def _import_course_draft( for draft in get_draft_subtree_roots(drafts): try: - _import_module(draft.module) + _import_block(draft.module) except Exception: # pylint: disable=broad-except logging.exception(f'Course import {source_course_id}: while importing draft descriptor {draft.module}') @@ -1059,89 +1059,89 @@ def allowed_metadata_by_category(category): }.get(category, ['*']) -def check_module_metadata_editability(module): +def check_block_metadata_editability(block): """ - Assert that there is no metadata within a particular module that + Assert that there is no metadata within a particular block that we can't support editing. However we always allow 'display_name' and 'xml_attributes' """ - allowed = allowed_metadata_by_category(module.location.block_type) + allowed = allowed_metadata_by_category(block.location.block_type) if '*' in allowed: # everything is allowed return 0 allowed = allowed + ['xml_attributes', 'display_name'] err_cnt = 0 - illegal_keys = set(own_metadata(module).keys()) - set(allowed) + illegal_keys = set(own_metadata(block).keys()) - set(allowed) if len(illegal_keys) > 0: err_cnt = err_cnt + 1 print( ": found non-editable metadata on {url}. " "These metadata keys are not supported = {keys}".format( - url=str(module.location), keys=illegal_keys + url=str(block.location), keys=illegal_keys ) ) return err_cnt -def get_parent_url(module, xml=None): +def get_parent_url(block, xml=None): """ - Get the parent_url, if any, from module using xml as an alternative source. If it finds it in - xml but not on module, it modifies module so that the next call to this w/o the xml will get the parent url + Get the parent_url, if any, from block using xml as an alternative source. If it finds it in + xml but not on block, it modifies block so that the next call to this w/o the xml will get the parent url """ - if hasattr(module, 'xml_attributes'): - return module.xml_attributes.get( + if hasattr(block, 'xml_attributes'): + return block.xml_attributes.get( # handle deprecated old attr - 'parent_url', module.xml_attributes.get('parent_sequential_url') + 'parent_url', block.xml_attributes.get('parent_sequential_url') ) if xml is not None: - create_xml_attributes(module, xml) - return get_parent_url(module) # don't reparse xml b/c don't infinite recurse but retry above lines + create_xml_attributes(block, xml) + return get_parent_url(block) # don't reparse xml b/c don't infinite recurse but retry above lines return None -def index_in_children_list(module, xml=None): +def index_in_children_list(block, xml=None): """ - Get the index_in_children_list, if any, from module using xml - as an alternative source. If it finds it in xml but not on module, - it modifies module so that the next call to this w/o the xml + Get the index_in_children_list, if any, from block using xml + as an alternative source. If it finds it in xml but not on block, + it modifies block so that the next call to this w/o the xml will get the field. """ - if hasattr(module, 'xml_attributes'): - val = module.xml_attributes.get('index_in_children_list') + if hasattr(block, 'xml_attributes'): + val = block.xml_attributes.get('index_in_children_list') if val is not None: return int(val) return None if xml is not None: - create_xml_attributes(module, xml) - return index_in_children_list(module) # don't reparse xml b/c don't infinite recurse but retry above lines + create_xml_attributes(block, xml) + return index_in_children_list(block) # don't reparse xml b/c don't infinite recurse but retry above lines return None -def create_xml_attributes(module, xml): +def create_xml_attributes(block, xml): """ - Make up for modules which don't define xml_attributes by creating them here and populating + Make up for blocks which don't define xml_attributes by creating them here and populating """ xml_attrs = {} for attr, val in xml.attrib.items(): - if attr not in module.fields: + if attr not in block.fields: # translate obsolete attr if attr == 'parent_sequential_url': attr = 'parent_url' xml_attrs[attr] = val - # now cache it on module where it's expected - module.xml_attributes = xml_attrs + # now cache it on block where it's expected + block.xml_attributes = xml_attrs def validate_no_non_editable_metadata(module_store, course_id, category): # lint-amnesty, pylint: disable=missing-function-docstring err_cnt = 0 - for module_loc in module_store.modules[course_id]: - module = module_store.modules[course_id][module_loc] - if module.location.block_type == category: - err_cnt = err_cnt + check_module_metadata_editability(module) + for block_loc in module_store.modules[course_id]: + block = module_store.modules[course_id][block_loc] + if block.location.block_type == category: + err_cnt = err_cnt + check_block_metadata_editability(block) return err_cnt @@ -1151,10 +1151,10 @@ def validate_category_hierarchy( # lint-amnesty, pylint: disable=missing-functi err_cnt = 0 parents = [] - # get all modules of parent_category - for module in module_store.modules[course_id].values(): - if module.location.block_type == parent_category: - parents.append(module) + # get all blocks of parent_category + for block in module_store.modules[course_id].values(): + if block.location.block_type == parent_category: + parents.append(block) for parent in parents: for child_loc in parent.children: @@ -1206,18 +1206,18 @@ def validate_course_policy(module_store, course_id): Does not add to error count as these are just warnings. """ - # is there a reliable way to get the module location just given the course_id? + # is there a reliable way to get the block location just given the course_id? warn_cnt = 0 - for module in module_store.modules[course_id].values(): - if module.location.block_type == 'course': - if not module._field_data.has(module, 'rerandomize'): # lint-amnesty, pylint: disable=protected-access + for block in module_store.modules[course_id].values(): + if block.location.block_type == 'course': + if not block._field_data.has(block, 'rerandomize'): # lint-amnesty, pylint: disable=protected-access warn_cnt += 1 print( 'WARN: course policy does not specify value for ' '"rerandomize" whose default is now "never". ' 'The behavior of your course may change.' ) - if not module._field_data.has(module, 'showanswer'): # lint-amnesty, pylint: disable=protected-access + if not block._field_data.has(block, 'showanswer'): # lint-amnesty, pylint: disable=protected-access warn_cnt += 1 print( 'WARN: course policy does not specify value for ' @@ -1230,7 +1230,7 @@ def validate_course_policy(module_store, course_id): def perform_xlint( # lint-amnesty, pylint: disable=missing-function-docstring data_dir, source_dirs, default_class='xmodule.hidden_block.HiddenBlock', - load_error_modules=True, + load_error_blocks=True, xblock_mixins=(LocationMixin, XModuleMixin)): err_cnt = 0 warn_cnt = 0 @@ -1239,7 +1239,7 @@ def perform_xlint( # lint-amnesty, pylint: disable=missing-function-docstring data_dir, default_class=default_class, source_dirs=source_dirs, - load_error_modules=load_error_modules, + load_error_blocks=load_error_blocks, xblock_mixins=xblock_mixins ) @@ -1329,16 +1329,16 @@ def perform_xlint( # lint-amnesty, pylint: disable=missing-function-docstring return err_cnt -def _update_module_location(module, new_location): +def _update_block_location(block, new_location): """ - Update a module's location. + Update a block's location. - If the module is a pure XBlock (not an XModule), then its field data + If the block is a pure XBlock (not an XModule), then its field data keys will need to be updated to include the new location. Args: - module (XModuleMixin): The module to update. - new_location (Location): The new location of the module. + block (XModuleMixin): The block to update. + new_location (Location): The new location of the block. Returns: None @@ -1347,12 +1347,12 @@ def _update_module_location(module, new_location): # Retrieve the content and settings fields that have been explicitly set # to ensure that they are properly re-keyed in the XBlock field data. rekey_fields = ( - list(module.get_explicitly_set_fields_by_scope(Scope.content).keys()) + - list(module.get_explicitly_set_fields_by_scope(Scope.settings).keys()) + - list(module.get_explicitly_set_fields_by_scope(Scope.children).keys()) + list(block.get_explicitly_set_fields_by_scope(Scope.content).keys()) + + list(block.get_explicitly_set_fields_by_scope(Scope.settings).keys()) + + list(block.get_explicitly_set_fields_by_scope(Scope.children).keys()) ) - module.location = new_location + block.location = new_location # Pure XBlocks store the field data in a key-value store # in which one component of the key is the XBlock's location (equivalent to "scope_ids"). @@ -1361,4 +1361,4 @@ def _update_module_location(module, new_location): # However, since XBlocks only save "dirty" fields, we need to call # XBlock's `force_save_fields_method` if len(rekey_fields) > 0: - module.force_save_fields(rekey_fields) + block.force_save_fields(rekey_fields) diff --git a/xmodule/progress.py b/xmodule/progress.py index 014ce6369f..dda88ad53e 100644 --- a/xmodule/progress.py +++ b/xmodule/progress.py @@ -1,5 +1,5 @@ ''' -Progress class for modules. Represents where a student is in a module. +Progress class for blocks. Represents where a student is in a block. For most subclassing needs, you should only need to reimplement frac() and __str__(). @@ -15,8 +15,8 @@ class Progress: a and b must be numeric, but not necessarily integer, with 0 <= a <= b and b > 0. - Progress can only represent Progress for modules where that makes sense. Other - modules (e.g. html) should return None from get_progress(). + Progress can only represent Progress for blocks where that makes sense. Other + blocks (e.g. html) should return None from get_progress(). TODO: add tag for module type? Would allow for smarter merging. ''' diff --git a/xmodule/randomize_block.py b/xmodule/randomize_block.py index a9c6a706df..abf3c2abb2 100644 --- a/xmodule/randomize_block.py +++ b/xmodule/randomize_block.py @@ -42,14 +42,14 @@ class RandomizeBlock( User notes: - - If you're randomizing amongst graded modules, each of them MUST be worth the same + - If you're randomizing amongst graded blocks, each of them MUST be worth the same number of points. Otherwise, the earth will be overrun by monsters from the deeps. You have been warned. Technical notes: - There is more dark magic in this code than I'd like. The whole varying-children + grading interaction is a tangle between super and subclasses of descriptors and - modules. + blocks. """ choice = Integer(help="Which random child was chosen", scope=Scope.user_state) @@ -120,6 +120,6 @@ class RandomizeBlock( def has_dynamic_children(self): """ Grading needs to know that only one of the children is actually "real". This - makes it use module.get_child_descriptors(). + makes it use block.get_child_descriptors(). """ return True diff --git a/xmodule/raw_block.py b/xmodule/raw_block.py index 06668e3d46..2b88e4a3a2 100644 --- a/xmodule/raw_block.py +++ b/xmodule/raw_block.py @@ -18,7 +18,7 @@ class RawMixin: """ resources_dir = None - data = String(help="XML data for the module", default="", scope=Scope.content) + data = String(help="XML data for the block", default="", scope=Scope.content) @classmethod def definition_from_xml(cls, xml_object, system): # lint-amnesty, pylint: disable=missing-function-docstring, unused-argument @@ -52,7 +52,7 @@ class RawMixin: lines = self.data.split('\n') line, offset = err.position msg = ( - "Unable to create xml for module {loc}. " + "Unable to create xml for block {loc}. " "Context: '{context}'" ).format( context=lines[line - 1][offset - 40:offset + 40], diff --git a/xmodule/seq_block.py b/xmodule/seq_block.py index 8e97a3e859..ccee922693 100644 --- a/xmodule/seq_block.py +++ b/xmodule/seq_block.py @@ -1,5 +1,5 @@ """ -xModule implementation of a learning sequence +XBlock implementation of a learning sequence """ # pylint: disable=abstract-method @@ -39,7 +39,7 @@ from .exceptions import NotFoundError from .fields import Date from .mako_block import MakoTemplateBlockBase from .progress import Progress -from .x_module import AUTHOR_VIEW, PUBLIC_VIEW, STUDENT_VIEW +from .x_module import AUTHOR_VIEW, PUBLIC_VIEW from .xml_block import XmlMixin diff --git a/xmodule/split_test_block.py b/xmodule/split_test_block.py index 9e3a7575a7..f7ae0f9d96 100644 --- a/xmodule/split_test_block.py +++ b/xmodule/split_test_block.py @@ -1,5 +1,5 @@ """ -Module for running content split tests +Block for running content split tests """ @@ -107,7 +107,7 @@ class SplitTestFields: # Block. (expected invariant that we'll need to test, and handle # authoring tools that mess this up) group_id_to_child = ReferenceValueDict( - help=_("Which child module students in a particular group_id should see"), + help=_("Which child block students in a particular group_id should see"), scope=Scope.content ) @@ -115,7 +115,7 @@ class SplitTestFields: def get_split_user_partitions(user_partitions): """ Helper method that filters a list of user_partitions and returns just the - ones that are suitable for the split_test module. + ones that are suitable for the split_test block. """ return [user_partition for user_partition in user_partitions if user_partition.scheme.name == "random"] @@ -148,7 +148,7 @@ class SplitTestBlock( # lint-amnesty, pylint: disable=abstract-method Technical notes: - There is more dark magic in this code than I'd like. The whole varying-children + grading interaction is a tangle between super and subclasses of descriptors and - modules. + blocks. """ resources_dir = 'assets/split_test' @@ -467,7 +467,7 @@ class SplitTestBlock( # lint-amnesty, pylint: disable=abstract-method descriptor = system.process_xml(etree.tostring(child)) children.append(descriptor.scope_ids.usage_id) except Exception: # lint-amnesty, pylint: disable=broad-except - msg = "Unable to load child when parsing split_test module." + msg = "Unable to load child when parsing split_test block." log.exception(msg) system.error_tracker(msg) @@ -486,7 +486,7 @@ class SplitTestBlock( # lint-amnesty, pylint: disable=abstract-method def has_dynamic_children(self): """ Grading needs to know that only one of the children is actually "real". This - makes it use module.get_child_descriptors(). + makes it use block.get_child_descriptors(). """ return True @@ -540,7 +540,7 @@ class SplitTestBlock( # lint-amnesty, pylint: disable=abstract-method def get_selected_partition(self): """ - Returns the partition that this split module is currently using, or None + Returns the partition that this split block is currently using, or None if the currently selected partition ID does not match any of the defined partitions. """ for user_partition in self.user_partitions: # lint-amnesty, pylint: disable=not-an-iterable @@ -637,7 +637,7 @@ class SplitTestBlock( # lint-amnesty, pylint: disable=abstract-method ) ) else: - # If the user_partition selected is not valid for the split_test module, error. + # If the user_partition selected is not valid for the split_test block, error. # This can only happen via XML and import/export. if not get_split_user_partitions([user_partition]): split_validation.add( diff --git a/xmodule/studio_editable.py b/xmodule/studio_editable.py index 287d72bab7..69d3126338 100644 --- a/xmodule/studio_editable.py +++ b/xmodule/studio_editable.py @@ -16,7 +16,7 @@ class StudioEditableBlock(XBlockMixin): def render_children(self, context, fragment, can_reorder=False, can_add=False): """ - Renders the children of the module with HTML appropriate for Studio. If can_reorder is True, + Renders the children of the block with HTML appropriate for Studio. If can_reorder is True, then the children will be rendered to support drag and drop. """ contents = [] @@ -43,7 +43,7 @@ class StudioEditableBlock(XBlockMixin): @staticmethod def get_preview_view_name(block): """ - Helper method for getting preview view name (student_view or author_view) for a given module. + Helper method for getting preview view name (student_view or author_view) for a given block. """ return AUTHOR_VIEW if has_author_view(block) else STUDENT_VIEW diff --git a/xmodule/template_block.py b/xmodule/template_block.py index 2c542ba4fc..eff6e07343 100644 --- a/xmodule/template_block.py +++ b/xmodule/template_block.py @@ -42,7 +42,7 @@ class CustomTagTemplateBlock( # pylint: disable=abstract-method @XBlock.needs('mako') class CustomTagBlock(CustomTagTemplateBlock): # pylint: disable=abstract-method """ - This module supports tags of the form + This block supports tags of the form In this case, $tagname should refer to a file in data/custom_tags, which diff --git a/xmodule/tests/helpers.py b/xmodule/tests/helpers.py index 8c960a2b57..2f7a399ab0 100644 --- a/xmodule/tests/helpers.py +++ b/xmodule/tests/helpers.py @@ -42,7 +42,7 @@ def mock_render_template(*args, **kwargs): class StubMakoService: """ - Stub MakoService for testing modules that use mako templates. + Stub MakoService for testing blocks that use mako templates. """ def __init__(self, render_template=None): @@ -57,7 +57,7 @@ class StubMakoService: class StubUserService(UserService): """ - Stub UserService for testing the sequence module. + Stub UserService for testing the sequence block. """ def __init__(self, @@ -101,7 +101,7 @@ class StubUserService(UserService): class StubReplaceURLService: """ - Stub ReplaceURLService for testing modules. + Stub ReplaceURLService for testing blocks. """ def replace_urls(self, text, static_replace_only=False): diff --git a/xmodule/tests/test_annotatable_block.py b/xmodule/tests/test_annotatable_block.py index b83be2248e..b9f419ee3a 100644 --- a/xmodule/tests/test_annotatable_block.py +++ b/xmodule/tests/test_annotatable_block.py @@ -1,4 +1,4 @@ -"""Module annotatable tests""" +"""Annotatable block tests""" import unittest diff --git a/xmodule/tests/test_capa_block.py b/xmodule/tests/test_capa_block.py index ac9726a0bc..bce2069844 100644 --- a/xmodule/tests/test_capa_block.py +++ b/xmodule/tests/test_capa_block.py @@ -42,7 +42,7 @@ from . import get_test_system class CapaFactory: """ - A helper class to create problem modules with various parameters for testing. + A helper class to create problem blocks with various parameters for testing. """ sample_problem_xml = textwrap.dedent("""\ @@ -93,8 +93,7 @@ class CapaFactory: force_save_button: rerandomize: all strings, as specified in the policy for the problem - problem_state: a dict to to be serialized into the instance_state of the - module. + problem_state: a dict to be serialized into the instance_state of the block. attempts: also added to instance state. Will be converted to an int. @@ -122,23 +121,23 @@ class CapaFactory: user_is_staff=kwargs.get('user_is_staff', False), render_template=render_template or Mock(return_value="
    Test Template HTML
    "), ) - module = ProblemBlock( + block = ProblemBlock( system, DictFieldData(field_data), ScopeIds(None, 'problem', location, location), ) - assert module.lcp + assert block.lcp if override_get_score: if correct: # TODO: probably better to actually set the internal state properly, but... - module.score = Score(raw_earned=1, raw_possible=1) + block.score = Score(raw_earned=1, raw_possible=1) else: - module.score = Score(raw_earned=0, raw_possible=1) + block.score = Score(raw_earned=0, raw_possible=1) - module.graded = 'False' - module.weight = 1 - return module + block.graded = 'False' + block.weight = 1 + return block class CapaFactoryWithFiles(CapaFactory): @@ -198,22 +197,22 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss self.two_day_delta_str = "2 days" def test_import(self): - module = CapaFactory.create() - assert module.get_score().raw_earned == 0 + block = CapaFactory.create() + assert block.get_score().raw_earned == 0 - other_module = CapaFactory.create() - assert module.get_score().raw_earned == 0 - assert module.url_name != other_module.url_name, 'Factory should be creating unique names for each problem' + other_block = CapaFactory.create() + assert block.get_score().raw_earned == 0 + assert block.url_name != other_block.url_name, 'Factory should be creating unique names for each problem' def test_correct(self): """ Check that the factory creates correct and incorrect problems properly. """ - module = CapaFactory.create() - assert module.get_score().raw_earned == 0 + block = CapaFactory.create() + assert block.get_score().raw_earned == 0 - other_module = CapaFactory.create(correct=True) - assert other_module.get_score().raw_earned == 1 + other_block = CapaFactory.create(correct=True) + assert other_block.get_score().raw_earned == 1 def test_get_score(self): """ @@ -223,20 +222,20 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ student_answers = {'1_2_1': 'abcd'} correct_map = CorrectMap(answer_id='1_2_1', correctness="correct", npoints=0.9) - module = CapaFactory.create(correct=True, override_get_score=False) - module.lcp.correct_map = correct_map - module.lcp.student_answers = student_answers - assert module.get_score().raw_earned == 0.0 - module.set_score(module.score_from_lcp(module.lcp)) - assert module.get_score().raw_earned == 0.9 + block = CapaFactory.create(correct=True, override_get_score=False) + block.lcp.correct_map = correct_map + block.lcp.student_answers = student_answers + assert block.get_score().raw_earned == 0.0 + block.set_score(block.score_from_lcp(block.lcp)) + assert block.get_score().raw_earned == 0.9 other_correct_map = CorrectMap(answer_id='1_2_1', correctness="incorrect", npoints=0.1) - other_module = CapaFactory.create(correct=False, override_get_score=False) - other_module.lcp.correct_map = other_correct_map - other_module.lcp.student_answers = student_answers - assert other_module.get_score().raw_earned == 0.0 - other_module.set_score(other_module.score_from_lcp(other_module.lcp)) - assert other_module.get_score().raw_earned == 0.1 + other_block = CapaFactory.create(correct=False, override_get_score=False) + other_block.lcp.correct_map = other_correct_map + other_block.lcp.student_answers = student_answers + assert other_block.get_score().raw_earned == 0.0 + other_block.set_score(other_block.score_from_lcp(other_block.lcp)) + assert other_block.get_score().raw_earned == 0.1 def test_showanswer_default(self): """ @@ -625,29 +624,29 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss def test_closed(self): # Attempts < Max attempts --> NOT closed - module = CapaFactory.create(max_attempts="1", attempts="0") - assert not module.closed() + block = CapaFactory.create(max_attempts="1", attempts="0") + assert not block.closed() # Attempts < Max attempts --> NOT closed - module = CapaFactory.create(max_attempts="2", attempts="1") - assert not module.closed() + block = CapaFactory.create(max_attempts="2", attempts="1") + assert not block.closed() # Attempts = Max attempts --> closed - module = CapaFactory.create(max_attempts="1", attempts="1") - assert module.closed() + block = CapaFactory.create(max_attempts="1", attempts="1") + assert block.closed() # Attempts > Max attempts --> closed - module = CapaFactory.create(max_attempts="1", attempts="2") - assert module.closed() + block = CapaFactory.create(max_attempts="1", attempts="2") + assert block.closed() # Max attempts = 0 --> closed - module = CapaFactory.create(max_attempts="0", attempts="2") - assert module.closed() + block = CapaFactory.create(max_attempts="0", attempts="2") + assert block.closed() # Past due --> closed - module = CapaFactory.create(max_attempts="1", attempts="0", - due=self.yesterday_str) - assert module.closed() + block = CapaFactory.create(max_attempts="1", attempts="0", + due=self.yesterday_str) + assert block.closed() def test_parse_get_params(self): @@ -699,7 +698,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss def test_submit_problem_correct(self): - module = CapaFactory.create(attempts=1) + block = CapaFactory.create(attempts=1) # Simulate that all answers are marked correct, no matter # what the input is, by patching CorrectMap.is_correct() @@ -711,7 +710,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Check the problem get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect that the problem is marked correct assert result['success'] == 'correct' @@ -720,13 +719,13 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss assert result['contents'] == 'Test HTML' # Expect that the number of attempts is incremented by 1 - assert module.attempts == 2 + assert block.attempts == 2 # and that this was considered attempt number 2 for grading purposes - assert module.lcp.context['attempt'] == 2 + assert block.lcp.context['attempt'] == 2 def test_submit_problem_incorrect(self): - module = CapaFactory.create(attempts=0) + block = CapaFactory.create(attempts=0) # Simulate marking the input incorrect with patch('xmodule.capa.correctmap.CorrectMap.is_correct') as mock_is_correct: @@ -734,18 +733,18 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Check the problem get_request_dict = {CapaFactory.input_key(): '0'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect that the problem is marked correct assert result['success'] == 'incorrect' # Expect that the number of attempts is incremented by 1 - assert module.attempts == 1 + assert block.attempts == 1 # and that this is considered the first attempt - assert module.lcp.context['attempt'] == 1 + assert block.lcp.context['attempt'] == 1 def test_submit_problem_closed(self): - module = CapaFactory.create(attempts=3) + block = CapaFactory.create(attempts=3) # Problem closed -- cannot submit # Simulate that ProblemBlock.closed() always returns True @@ -753,10 +752,10 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss mock_closed.return_value = True with pytest.raises(xmodule.exceptions.NotFoundError): get_request_dict = {CapaFactory.input_key(): '3.14'} - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) # Expect that number of attempts NOT incremented - assert module.attempts == 3 + assert block.attempts == 3 @ddt.data( RANDOMIZATION.ALWAYS, @@ -764,18 +763,18 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss ) def test_submit_problem_resubmitted_with_randomize(self, rerandomize): # Randomize turned on - module = CapaFactory.create(rerandomize=rerandomize, attempts=0) + block = CapaFactory.create(rerandomize=rerandomize, attempts=0) # Simulate that the problem is completed - module.done = True + block.done = True # Expect that we cannot submit with pytest.raises(xmodule.exceptions.NotFoundError): get_request_dict = {CapaFactory.input_key(): '3.14'} - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) # Expect that number of attempts NOT incremented - assert module.attempts == 0 + assert block.attempts == 0 @ddt.data( RANDOMIZATION.NEVER, @@ -784,20 +783,20 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss ) def test_submit_problem_resubmitted_no_randomize(self, rerandomize): # Randomize turned off - module = CapaFactory.create(rerandomize=rerandomize, attempts=0, done=True) + block = CapaFactory.create(rerandomize=rerandomize, attempts=0, done=True) # Expect that we can submit successfully get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) assert result['success'] == 'correct' # Expect that number of attempts IS incremented, still same attempt - assert module.attempts == 1 - assert module.lcp.context['attempt'] == 1 + assert block.attempts == 1 + assert block.lcp.context['attempt'] == 1 def test_submit_problem_queued(self): - module = CapaFactory.create(attempts=1) + block = CapaFactory.create(attempts=1) # Simulate that the problem is queued multipatch = patch.multiple( @@ -810,13 +809,13 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss values['get_recentmost_queuetime'].return_value = datetime.datetime.now(UTC) get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect an AJAX alert message in 'success' assert 'You must wait' in result['success'] # Expect that the number of attempts is NOT incremented - assert module.attempts == 1 + assert block.attempts == 1 @patch.object(XQueueInterface, '_http_post') def test_submit_problem_with_files(self, mock_xqueue_post): @@ -830,7 +829,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss for fileobj in fileobjs: self.addCleanup(fileobj.close) - module = CapaFactoryWithFiles.create() + block = CapaFactoryWithFiles.create() # Mock the XQueueInterface post method mock_xqueue_post.return_value = (0, "ok") @@ -841,7 +840,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss CapaFactoryWithFiles.input_key(response_num=3): 'None', } - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) # pylint: disable=line-too-long # _http_post is called like this: @@ -880,7 +879,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss for fileobj in fileobjs: self.addCleanup(fileobj.close) - module = CapaFactoryWithFiles.create() + block = CapaFactoryWithFiles.create() # Mock the XQueueInterface post method mock_xqueue_post.return_value = (0, "ok") @@ -892,7 +891,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss post_data.append((CapaFactoryWithFiles.input_key(response_num=3), 'None')) request = webob.Request.blank("/some/fake/url", POST=post_data, content_type='multipart/form-data') - module.handle('xmodule_handler', request, 'problem_check') + block.handle('xmodule_handler', request, 'problem_check') assert mock_xqueue_post.call_count == 1 _, kwargs = mock_xqueue_post.call_args @@ -907,15 +906,15 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss LoncapaProblemError, ResponseError] for exception_class in exception_classes: - # Create the module - module = CapaFactory.create(attempts=1, user_is_staff=False) + # Create the block + block = CapaFactory.create(attempts=1, user_is_staff=False) # Simulate answering a problem that raises the exception with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade: mock_grade.side_effect = exception_class('test error') get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect an AJAX alert message in 'success' expected_msg = 'test error' @@ -923,9 +922,9 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss assert expected_msg == result['success'] # Expect that the number of attempts is NOT incremented - assert module.attempts == 1 + assert block.attempts == 1 # but that this was considered attempt number 2 for grading purposes - assert module.lcp.context['attempt'] == 2 + assert block.lcp.context['attempt'] == 2 def test_submit_problem_error_with_codejail_exception(self): @@ -935,8 +934,8 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss ResponseError] for exception_class in exception_classes: - # Create the module - module = CapaFactory.create(attempts=1, user_is_staff=False) + # Create the block + block = CapaFactory.create(attempts=1, user_is_staff=False) # Simulate a codejail exception "Exception: Couldn't execute jailed code" with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade: @@ -951,16 +950,16 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss except ResponseError as err: mock_grade.side_effect = exception_class(str(err)) get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect an AJAX alert message in 'success' without the text of the stack trace expected_msg = 'Couldn\'t execute jailed code' assert expected_msg == result['success'] # Expect that the number of attempts is NOT incremented - assert module.attempts == 1 + assert block.attempts == 1 # but that this was considered the second attempt for grading purposes - assert module.lcp.context['attempt'] == 2 + assert block.lcp.context['attempt'] == 2 @override_settings(DEBUG=True) def test_submit_problem_other_errors(self): @@ -969,8 +968,8 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss See also `test_submit_problem_error` for the "expected kinds" or errors. """ - # Create the module - module = CapaFactory.create(attempts=1, user_is_staff=False) + # Create the block + block = CapaFactory.create(attempts=1, user_is_staff=False) # Simulate answering a problem that raises the exception with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade: @@ -978,7 +977,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss mock_grade.side_effect = Exception(error_msg) get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect an AJAX alert message in 'success' assert error_msg in result['success'] @@ -987,15 +986,15 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ Test that a capa problem with a max grade of zero doesn't generate an error. """ - # Create the module - module = CapaFactory.create(attempts=1) + # Create the block + block = CapaFactory.create(attempts=1) # Override the problem score to have a total of zero. - module.lcp.get_score = lambda: {'score': 0, 'total': 0} + block.lcp.get_score = lambda: {'score': 0, 'total': 0} # Check the problem get_request_dict = {CapaFactory.input_key(): '3.14'} - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) def test_submit_problem_error_nonascii(self): @@ -1004,15 +1003,15 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss LoncapaProblemError, ResponseError] for exception_class in exception_classes: - # Create the module - module = CapaFactory.create(attempts=1, user_is_staff=False) + # Create the block + block = CapaFactory.create(attempts=1, user_is_staff=False) # Simulate answering a problem that raises the exception with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade: mock_grade.side_effect = exception_class("ȧƈƈḗƞŧḗḓ ŧḗẋŧ ƒǿř ŧḗşŧīƞɠ") get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect an AJAX alert message in 'success' expected_msg = 'ȧƈƈḗƞŧḗḓ ŧḗẋŧ ƒǿř ŧḗşŧīƞɠ' @@ -1020,9 +1019,9 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss assert expected_msg == result['success'] # Expect that the number of attempts is NOT incremented - assert module.attempts == 1 + assert block.attempts == 1 # but that this was considered the second attempt for grading purposes - assert module.lcp.context['attempt'] == 2 + assert block.lcp.context['attempt'] == 2 def test_submit_problem_error_with_staff_user(self): @@ -1030,15 +1029,15 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss for exception_class in [StudentInputError, LoncapaProblemError, ResponseError]: - # Create the module - module = CapaFactory.create(attempts=1, user_is_staff=True) + # Create the block + block = CapaFactory.create(attempts=1, user_is_staff=True) # Simulate answering a problem that raises an exception with patch('xmodule.capa.capa_problem.LoncapaProblem.grade_answers') as mock_grade: mock_grade.side_effect = exception_class('test error') get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect an AJAX alert message in 'success' assert 'test error' in result['success'] @@ -1047,9 +1046,9 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss assert 'Traceback' in result['success'] # Expect that the number of attempts is NOT incremented - assert module.attempts == 1 + assert block.attempts == 1 # but that it was considered the second attempt for grading purposes - assert module.lcp.context['attempt'] == 2 + assert block.lcp.context['attempt'] == 2 @ddt.data( ("never", True, None, 'submitted'), @@ -1061,9 +1060,9 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss ) @ddt.unpack def test_handle_ajax_show_correctness(self, show_correctness, is_correct, expected_score, expected_success): - module = CapaFactory.create(show_correctness=show_correctness, - due=self.tomorrow_str, - correct=is_correct) + block = CapaFactory.create(show_correctness=show_correctness, + due=self.tomorrow_str, + correct=is_correct) # Simulate marking the input correct/incorrect with patch('xmodule.capa.correctmap.CorrectMap.is_correct') as mock_is_correct: @@ -1071,7 +1070,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Check the problem get_request_dict = {CapaFactory.input_key(): '0'} - json_result = module.handle_ajax('problem_check', get_request_dict) + json_result = block.handle_ajax('problem_check', get_request_dict) result = json.loads(json_result) # Expect that the AJAX result withholds correctness and score @@ -1079,13 +1078,13 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss assert result['success'] == expected_success # Expect that the number of attempts is incremented by 1 - assert module.attempts == 1 - assert module.lcp.context['attempt'] == 1 + assert block.attempts == 1 + assert block.lcp.context['attempt'] == 1 def test_reset_problem(self): - module = CapaFactory.create(done=True) - module.new_lcp = Mock(wraps=module.new_lcp) - module.choose_new_seed = Mock(wraps=module.choose_new_seed) + block = CapaFactory.create(done=True) + block.new_lcp = Mock(wraps=block.new_lcp) + block.choose_new_seed = Mock(wraps=block.choose_new_seed) # Stub out HTML rendering with patch('xmodule.capa_block.ProblemBlock.get_problem_html') as mock_html: @@ -1093,7 +1092,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Reset the problem get_request_dict = {} - result = module.reset_problem(get_request_dict) + result = block.reset_problem(get_request_dict) # Expect that the request was successful assert (('success' in result) and result['success']) @@ -1103,11 +1102,11 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss assert result['html'] == '
    Test HTML
    ' # Expect that the problem was reset - module.new_lcp.assert_called_once_with(None) + block.new_lcp.assert_called_once_with(None) def test_reset_problem_closed(self): # pre studio default - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS) + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS) # Simulate that the problem is closed with patch('xmodule.capa_block.ProblemBlock.closed') as mock_closed: @@ -1115,25 +1114,25 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Try to reset the problem get_request_dict = {} - result = module.reset_problem(get_request_dict) + result = block.reset_problem(get_request_dict) # Expect that the problem was NOT reset assert (('success' in result) and (not result['success'])) def test_reset_problem_not_done(self): # Simulate that the problem is NOT done - module = CapaFactory.create(done=False) + block = CapaFactory.create(done=False) # Try to reset the problem get_request_dict = {} - result = module.reset_problem(get_request_dict) + result = block.reset_problem(get_request_dict) # Expect that the problem was NOT reset assert (('success' in result) and (not result['success'])) def test_rescore_problem_correct(self): - module = CapaFactory.create(attempts=0, done=True) + block = CapaFactory.create(attempts=0, done=True) # Simulate that all answers are marked correct, no matter # what the input is, by patching LoncapaResponse.evaluate_answers() @@ -1148,91 +1147,91 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Check the problem get_request_dict = {CapaFactory.input_key(): '1'} - module.submit_problem(get_request_dict) - module.rescore(only_if_higher=False) + block.submit_problem(get_request_dict) + block.rescore(only_if_higher=False) # Expect that the problem is marked correct - assert module.is_correct() is True + assert block.is_correct() is True # Expect that the number of attempts is not incremented - assert module.attempts == 1 + assert block.attempts == 1 # and that this was considered attempt number 1 for grading purposes - assert module.lcp.context['attempt'] == 1 + assert block.lcp.context['attempt'] == 1 def test_rescore_problem_additional_correct(self): # make sure it also works when new correct answer has been added - module = CapaFactory.create(attempts=0) + block = CapaFactory.create(attempts=0) answer_id = CapaFactory.answer_key() # Check the problem get_request_dict = {CapaFactory.input_key(): '1'} - result = module.submit_problem(get_request_dict) + result = block.submit_problem(get_request_dict) # Expect that the problem is marked incorrect and user didn't earn score assert result['success'] == 'incorrect' - assert module.get_score() == (0, 1) - assert module.correct_map[answer_id]['correctness'] == 'incorrect' + assert block.get_score() == (0, 1) + assert block.correct_map[answer_id]['correctness'] == 'incorrect' # Expect that the number of attempts has incremented to 1 - assert module.attempts == 1 - assert module.lcp.context['attempt'] == 1 + assert block.attempts == 1 + assert block.lcp.context['attempt'] == 1 # Simulate that after making an incorrect answer to the correct answer # the new calculated score is (1,1) # by patching CorrectMap.is_correct() and NumericalResponse.get_staff_ans() - # In case of rescore with only_if_higher=True it should update score of module + # In case of rescore with only_if_higher=True it should update score of block # if previous score was lower with patch('xmodule.capa.correctmap.CorrectMap.is_correct') as mock_is_correct: mock_is_correct.return_value = True - module.set_score(module.score_from_lcp(module.lcp)) + block.set_score(block.score_from_lcp(block.lcp)) with patch('xmodule.capa.responsetypes.NumericalResponse.get_staff_ans') as get_staff_ans: get_staff_ans.return_value = 1 + 0j - module.rescore(only_if_higher=True) + block.rescore(only_if_higher=True) # Expect that the problem is marked correct and user earned the score - assert module.get_score() == (1, 1) - assert module.correct_map[answer_id]['correctness'] == 'correct' + assert block.get_score() == (1, 1) + assert block.correct_map[answer_id]['correctness'] == 'correct' # Expect that the number of attempts is not incremented - assert module.attempts == 1 + assert block.attempts == 1 # and hence that this was still considered the first attempt for grading purposes - assert module.lcp.context['attempt'] == 1 + assert block.lcp.context['attempt'] == 1 def test_rescore_problem_incorrect(self): # make sure it also works when attempts have been reset, # so add this to the test: - module = CapaFactory.create(attempts=0, done=True) + block = CapaFactory.create(attempts=0, done=True) # Simulate that all answers are marked incorrect, no matter # what the input is, by patching LoncapaResponse.evaluate_answers() with patch('xmodule.capa.responsetypes.LoncapaResponse.evaluate_answers') as mock_evaluate_answers: mock_evaluate_answers.return_value = CorrectMap(CapaFactory.answer_key(), 'incorrect') - module.rescore(only_if_higher=False) + block.rescore(only_if_higher=False) # Expect that the problem is marked incorrect - assert module.is_correct() is False + assert block.is_correct() is False # Expect that the number of attempts is not incremented - assert module.attempts == 0 + assert block.attempts == 0 # and that this is treated as the first attempt for grading purposes - assert module.lcp.context['attempt'] == 1 + assert block.lcp.context['attempt'] == 1 def test_rescore_problem_not_done(self): # Simulate that the problem is NOT done - module = CapaFactory.create(done=False) + block = CapaFactory.create(done=False) # Try to rescore the problem, and get exception with pytest.raises(xmodule.exceptions.NotFoundError): - module.rescore(only_if_higher=False) + block.rescore(only_if_higher=False) def test_rescore_problem_not_supported(self): - module = CapaFactory.create(done=True) + block = CapaFactory.create(done=True) # Try to rescore the problem, and get exception with patch('xmodule.capa.capa_problem.LoncapaProblem.supports_rescoring') as mock_supports_rescoring: mock_supports_rescoring.return_value = False with pytest.raises(NotImplementedError): - module.rescore(only_if_higher=False) + block.rescore(only_if_higher=False) def capa_factory_for_problem_xml(self, xml): # lint-amnesty, pylint: disable=missing-function-docstring class CustomCapaFactory(CapaFactory): @@ -1261,19 +1260,19 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss def _rescore_problem_error_helper(self, exception_class): """Helper to allow testing all errors that rescoring might return.""" - # Create the module - module = CapaFactory.create(attempts=1, done=True) + # Create the block + block = CapaFactory.create(attempts=1, done=True) # Simulate answering a problem that raises the exception with patch('xmodule.capa.capa_problem.LoncapaProblem.get_grade_from_current_answers') as mock_rescore: mock_rescore.side_effect = exception_class('test error \u03a9') with pytest.raises(exception_class): - module.rescore(only_if_higher=False) + block.rescore(only_if_higher=False) # Expect that the number of attempts is NOT incremented - assert module.attempts == 1 + assert block.attempts == 1 # and that this was considered the first attempt for grading purposes - assert module.lcp.context['attempt'] == 1 + assert block.lcp.context['attempt'] == 1 def test_rescore_problem_student_input_error(self): self._rescore_problem_error_helper(StudentInputError) @@ -1285,21 +1284,21 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss self._rescore_problem_error_helper(ResponseError) def test_save_problem(self): - module = CapaFactory.create(done=False) + block = CapaFactory.create(done=False) # Save the problem get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.save_problem(get_request_dict) + result = block.save_problem(get_request_dict) # Expect that answers are saved to the problem expected_answers = {CapaFactory.answer_key(): '3.14'} - assert module.lcp.student_answers == expected_answers + assert block.lcp.student_answers == expected_answers # Expect that the result is success assert (('success' in result) and result['success']) def test_save_problem_closed(self): - module = CapaFactory.create(done=False) + block = CapaFactory.create(done=False) # Simulate that the problem is closed with patch('xmodule.capa_block.ProblemBlock.closed') as mock_closed: @@ -1307,7 +1306,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Try to save the problem get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.save_problem(get_request_dict) + result = block.save_problem(get_request_dict) # Expect that the result is failure assert (('success' in result) and (not result['success'])) @@ -1318,11 +1317,11 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss ) def test_save_problem_submitted_with_randomize(self, rerandomize): # Capa XModule treats 'always' and 'true' equivalently - module = CapaFactory.create(rerandomize=rerandomize, done=True) + block = CapaFactory.create(rerandomize=rerandomize, done=True) # Try to save get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.save_problem(get_request_dict) + result = block.save_problem(get_request_dict) # Expect that we cannot save assert (('success' in result) and (not result['success'])) @@ -1333,198 +1332,198 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss RANDOMIZATION.PER_STUDENT ) def test_save_problem_submitted_no_randomize(self, rerandomize): - # Capa XModule treats 'false' and 'per_student' equivalently - module = CapaFactory.create(rerandomize=rerandomize, done=True) + # Capa XBlock treats 'false' and 'per_student' equivalently + block = CapaFactory.create(rerandomize=rerandomize, done=True) # Try to save get_request_dict = {CapaFactory.input_key(): '3.14'} - result = module.save_problem(get_request_dict) + result = block.save_problem(get_request_dict) # Expect that we succeed assert (('success' in result) and result['success']) def test_submit_button_name(self): - module = CapaFactory.create(attempts=0) - assert module.submit_button_name() == 'Submit' + block = CapaFactory.create(attempts=0) + assert block.submit_button_name() == 'Submit' def test_submit_button_submitting_name(self): - module = CapaFactory.create(attempts=1, max_attempts=10) - assert module.submit_button_submitting_name() == 'Submitting' + block = CapaFactory.create(attempts=1, max_attempts=10) + assert block.submit_button_submitting_name() == 'Submitting' def test_should_enable_submit_button(self): attempts = random.randint(1, 10) # If we're after the deadline, disable the submit button - module = CapaFactory.create(due=self.yesterday_str) - assert not module.should_enable_submit_button() + block = CapaFactory.create(due=self.yesterday_str) + assert not block.should_enable_submit_button() # If user is out of attempts, disable the submit button - module = CapaFactory.create(attempts=attempts, max_attempts=attempts) - assert not module.should_enable_submit_button() + block = CapaFactory.create(attempts=attempts, max_attempts=attempts) + assert not block.should_enable_submit_button() # If survey question (max_attempts = 0), disable the submit button - module = CapaFactory.create(max_attempts=0) - assert not module.should_enable_submit_button() + block = CapaFactory.create(max_attempts=0) + assert not block.should_enable_submit_button() # If user submitted a problem but hasn't reset, # disable the submit button # Note: we can only reset when rerandomize="always" or "true" - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=True) - assert not module.should_enable_submit_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=True) + assert not block.should_enable_submit_button() - module = CapaFactory.create(rerandomize="true", done=True) - assert not module.should_enable_submit_button() + block = CapaFactory.create(rerandomize="true", done=True) + assert not block.should_enable_submit_button() # Otherwise, enable the submit button - module = CapaFactory.create() - assert module.should_enable_submit_button() + block = CapaFactory.create() + assert block.should_enable_submit_button() # If the user has submitted the problem # and we do NOT have a reset button, then we can enable the submit button # Setting rerandomize to "never" or "false" ensures that the reset button # is not shown - module = CapaFactory.create(rerandomize=RANDOMIZATION.NEVER, done=True) - assert module.should_enable_submit_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.NEVER, done=True) + assert block.should_enable_submit_button() - module = CapaFactory.create(rerandomize="false", done=True) - assert module.should_enable_submit_button() + block = CapaFactory.create(rerandomize="false", done=True) + assert block.should_enable_submit_button() - module = CapaFactory.create(rerandomize=RANDOMIZATION.PER_STUDENT, done=True) - assert module.should_enable_submit_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.PER_STUDENT, done=True) + assert block.should_enable_submit_button() def test_should_show_reset_button(self): attempts = random.randint(1, 10) # If we're after the deadline, do NOT show the reset button - module = CapaFactory.create(due=self.yesterday_str, done=True) - assert not module.should_show_reset_button() + block = CapaFactory.create(due=self.yesterday_str, done=True) + assert not block.should_show_reset_button() # If the user is out of attempts, do NOT show the reset button - module = CapaFactory.create(attempts=attempts, max_attempts=attempts, done=True) - assert not module.should_show_reset_button() + block = CapaFactory.create(attempts=attempts, max_attempts=attempts, done=True) + assert not block.should_show_reset_button() # pre studio default value, DO show the reset button - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=True) - assert module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=True) + assert block.should_show_reset_button() # If survey question for capa (max_attempts = 0), # DO show the reset button - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, max_attempts=0, done=True) - assert module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, max_attempts=0, done=True) + assert block.should_show_reset_button() # If the question is not correct # DO show the reset button - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, max_attempts=0, done=True, correct=False) - assert module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, max_attempts=0, done=True, correct=False) + assert block.should_show_reset_button() # If the question is correct and randomization is never # DO not show the reset button - module = CapaFactory.create(rerandomize=RANDOMIZATION.NEVER, max_attempts=0, done=True, correct=True) - assert not module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.NEVER, max_attempts=0, done=True, correct=True) + assert not block.should_show_reset_button() # If the question is correct and randomization is always # Show the reset button - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, max_attempts=0, done=True, correct=True) - assert module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, max_attempts=0, done=True, correct=True) + assert block.should_show_reset_button() # Don't show reset button if randomization is turned on and the question is not done - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, show_reset_button=False, done=False) - assert not module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, show_reset_button=False, done=False) + assert not block.should_show_reset_button() # Show reset button if randomization is turned on and the problem is done - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, show_reset_button=False, done=True) - assert module.should_show_reset_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, show_reset_button=False, done=True) + assert block.should_show_reset_button() def test_should_show_save_button(self): attempts = random.randint(1, 10) # If we're after the deadline, do NOT show the save button - module = CapaFactory.create(due=self.yesterday_str, done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(due=self.yesterday_str, done=True) + assert not block.should_show_save_button() # If the user is out of attempts, do NOT show the save button - module = CapaFactory.create(attempts=attempts, max_attempts=attempts, done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(attempts=attempts, max_attempts=attempts, done=True) + assert not block.should_show_save_button() # If user submitted a problem but hasn't reset, do NOT show the save button - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=True) + assert not block.should_show_save_button() - module = CapaFactory.create(rerandomize="true", done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(rerandomize="true", done=True) + assert not block.should_show_save_button() # If the user has unlimited attempts and we are not randomizing, # then do NOT show a save button # because they can keep using "Check" - module = CapaFactory.create(max_attempts=None, rerandomize=RANDOMIZATION.NEVER, done=False) - assert not module.should_show_save_button() + block = CapaFactory.create(max_attempts=None, rerandomize=RANDOMIZATION.NEVER, done=False) + assert not block.should_show_save_button() - module = CapaFactory.create(max_attempts=None, rerandomize="false", done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(max_attempts=None, rerandomize="false", done=True) + assert not block.should_show_save_button() - module = CapaFactory.create(max_attempts=None, rerandomize=RANDOMIZATION.PER_STUDENT, done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(max_attempts=None, rerandomize=RANDOMIZATION.PER_STUDENT, done=True) + assert not block.should_show_save_button() # pre-studio default, DO show the save button - module = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=False) - assert module.should_show_save_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.ALWAYS, done=False) + assert block.should_show_save_button() # If we're not randomizing and we have limited attempts, then we can save - module = CapaFactory.create(rerandomize=RANDOMIZATION.NEVER, max_attempts=2, done=True) - assert module.should_show_save_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.NEVER, max_attempts=2, done=True) + assert block.should_show_save_button() - module = CapaFactory.create(rerandomize="false", max_attempts=2, done=True) - assert module.should_show_save_button() + block = CapaFactory.create(rerandomize="false", max_attempts=2, done=True) + assert block.should_show_save_button() - module = CapaFactory.create(rerandomize=RANDOMIZATION.PER_STUDENT, max_attempts=2, done=True) - assert module.should_show_save_button() + block = CapaFactory.create(rerandomize=RANDOMIZATION.PER_STUDENT, max_attempts=2, done=True) + assert block.should_show_save_button() # If survey question for capa (max_attempts = 0), # DO show the save button - module = CapaFactory.create(max_attempts=0, done=False) - assert module.should_show_save_button() + block = CapaFactory.create(max_attempts=0, done=False) + assert block.should_show_save_button() def test_should_show_save_button_force_save_button(self): # If we're after the deadline, do NOT show the save button # even though we're forcing a save - module = CapaFactory.create(due=self.yesterday_str, - force_save_button="true", - done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(due=self.yesterday_str, + force_save_button="true", + done=True) + assert not block.should_show_save_button() # If the user is out of attempts, do NOT show the save button attempts = random.randint(1, 10) - module = CapaFactory.create(attempts=attempts, - max_attempts=attempts, - force_save_button="true", - done=True) - assert not module.should_show_save_button() + block = CapaFactory.create(attempts=attempts, + max_attempts=attempts, + force_save_button="true", + done=True) + assert not block.should_show_save_button() # Otherwise, if we force the save button, # then show it even if we would ordinarily # require a reset first - module = CapaFactory.create(force_save_button="true", - rerandomize=RANDOMIZATION.ALWAYS, - done=True) - assert module.should_show_save_button() + block = CapaFactory.create(force_save_button="true", + rerandomize=RANDOMIZATION.ALWAYS, + done=True) + assert block.should_show_save_button() - module = CapaFactory.create(force_save_button="true", - rerandomize="true", - done=True) - assert module.should_show_save_button() + block = CapaFactory.create(force_save_button="true", + rerandomize="true", + done=True) + assert block.should_show_save_button() def test_no_max_attempts(self): - module = CapaFactory.create(max_attempts='') - html = module.get_problem_html() + block = CapaFactory.create(max_attempts='') + html = block.get_problem_html() assert html is not None # assert that we got here without exploding def test_get_problem_html(self): render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(render_template=render_template) + block = CapaFactory.create(render_template=render_template) # We've tested the show/hide button logic in other tests, # so here we hard-wire the values @@ -1532,19 +1531,19 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss show_reset_button = bool(random.randint(0, 1) % 2) show_save_button = bool(random.randint(0, 1) % 2) - module.should_enable_submit_button = Mock(return_value=enable_submit_button) - module.should_show_reset_button = Mock(return_value=show_reset_button) - module.should_show_save_button = Mock(return_value=show_save_button) + block.should_enable_submit_button = Mock(return_value=enable_submit_button) + block.should_show_reset_button = Mock(return_value=show_reset_button) + block.should_show_save_button = Mock(return_value=show_save_button) # Patch the capa problem's HTML rendering with patch('xmodule.capa.capa_problem.LoncapaProblem.get_html') as mock_html: mock_html.return_value = "
    Test Problem HTML
    " # Render the problem HTML - html = module.get_problem_html(encapsulate=False) + html = block.get_problem_html(encapsulate=False) # Also render the problem encapsulated in a
    - html_encapsulated = module.get_problem_html(encapsulate=True) + html_encapsulated = block.get_problem_html(encapsulate=True) # Expect that we get the rendered template back assert html == '
    Test Template HTML
    ' @@ -1586,22 +1585,22 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # HTML generation is mocked out to be meaningless here, so instead we check # the context dict passed into HTML generation. render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(xml=self.demand_xml, render_template=render_template) - module.get_problem_html() # ignoring html result + block = CapaFactory.create(xml=self.demand_xml, render_template=render_template) + block.get_problem_html() # ignoring html result context = render_template.call_args[0][1] assert context['demand_hint_possible'] assert context['should_enable_next_hint'] # Check the AJAX call that gets the hint by index - result = module.get_demand_hint(0) + result = block.get_demand_hint(0) assert result['hint_index'] == 0 assert result['should_enable_next_hint'] - result = module.get_demand_hint(1) + result = block.get_demand_hint(1) assert result['hint_index'] == 1 assert not result['should_enable_next_hint'] - result = module.get_demand_hint(2) # here the server wraps around to index 0 + result = block.get_demand_hint(2) # here the server wraps around to index 0 assert result['hint_index'] == 0 assert result['should_enable_next_hint'] @@ -1624,14 +1623,14 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(xml=test_xml, render_template=render_template) - module.get_problem_html() # ignoring html result + block = CapaFactory.create(xml=test_xml, render_template=render_template) + block.get_problem_html() # ignoring html result context = render_template.call_args[0][1] assert context['demand_hint_possible'] assert context['should_enable_next_hint'] # Check the AJAX call that gets the hint by index - result = module.get_demand_hint(0) + result = block.get_demand_hint(0) assert result['hint_index'] == 0 assert not result['should_enable_next_hint'] @@ -1656,14 +1655,14 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(xml=test_xml, render_template=render_template) - module.get_problem_html() # ignoring html result + block = CapaFactory.create(xml=test_xml, render_template=render_template) + block.get_problem_html() # ignoring html result context = render_template.call_args[0][1] assert context['demand_hint_possible'] assert context['should_enable_next_hint'] # Check the AJAX call that gets the hint by index - result = module.get_demand_hint(0) + result = block.get_demand_hint(0) assert result['hint_index'] == 0 assert not result['should_enable_next_hint'] @@ -1671,27 +1670,27 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ Test calling get_demand_hunt() results in an event being published. """ - module = CapaFactory.create(xml=self.demand_xml) - with patch.object(module.runtime, 'publish') as mock_publish: - module.get_problem_html() - module.get_demand_hint(0) + block = CapaFactory.create(xml=self.demand_xml) + with patch.object(block.runtime, 'publish') as mock_publish: + block.get_problem_html() + block.get_demand_hint(0) mock_publish.assert_called_with( - module, 'edx.problem.hint.demandhint_displayed', - {'hint_index': 0, 'module_id': str(module.location), + block, 'edx.problem.hint.demandhint_displayed', + {'hint_index': 0, 'module_id': str(block.location), 'hint_text': 'Demand 1', 'hint_len': 2} ) def test_input_state_consistency(self): - module1 = CapaFactory.create() - module2 = CapaFactory.create() + block1 = CapaFactory.create() + block2 = CapaFactory.create() # check to make sure that the input_state and the keys have the same values - module1.set_state_from_lcp() - assert list(module1.lcp.inputs.keys()) == list(module1.input_state.keys()) + block1.set_state_from_lcp() + assert list(block1.lcp.inputs.keys()) == list(block1.input_state.keys()) - module2.set_state_from_lcp() + block2.set_state_from_lcp() - intersection = set(module2.input_state.keys()).intersection(set(module1.input_state.keys())) + intersection = set(block2.input_state.keys()).intersection(set(block1.input_state.keys())) assert len(intersection) == 0 def test_get_problem_html_error(self): @@ -1701,17 +1700,17 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss message to display to the user. """ render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(render_template=render_template) + block = CapaFactory.create(render_template=render_template) # Save the original problem so we can compare it later - original_problem = module.lcp + original_problem = block.lcp # Simulate throwing an exception when the capa problem # is asked to render itself as HTML - module.lcp.get_html = Mock(side_effect=Exception("Test")) + block.lcp.get_html = Mock(side_effect=Exception("Test")) - # Try to render the module with DEBUG turned off - html = module.get_problem_html() + # Try to render the block with DEBUG turned off + html = block.get_problem_html() assert html is not None @@ -1720,25 +1719,25 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss context = render_args[1] assert 'error' in context['problem']['html'] - # Expect that the module has created a new dummy problem with the error - assert original_problem != module.lcp + # Expect that the block has created a new dummy problem with the error + assert original_problem != block.lcp def test_get_problem_html_error_preview(self): """ Test the html response when an error occurs with DEBUG off in Studio. """ render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(render_template=render_template) + block = CapaFactory.create(render_template=render_template) # Simulate throwing an exception when the capa problem # is asked to render itself as HTML error_msg = "Superterrible error happened: ☠" - module.lcp.get_html = Mock(side_effect=Exception(error_msg)) + block.lcp.get_html = Mock(side_effect=Exception(error_msg)) - module.system.is_author_mode = True + block.system.is_author_mode = True - # Try to render the module with the author mode turned on - html = module.get_problem_html() + # Try to render the block with the author mode turned on + html = block.get_problem_html() assert html is not None @@ -1753,15 +1752,15 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss Test the html response when an error occurs with DEBUG on """ render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(render_template=render_template) + block = CapaFactory.create(render_template=render_template) # Simulate throwing an exception when the capa problem # is asked to render itself as HTML error_msg = "Superterrible error happened: ☠" - module.lcp.get_html = Mock(side_effect=Exception(error_msg)) + block.lcp.get_html = Mock(side_effect=Exception(error_msg)) - # Try to render the module with DEBUG turned on - html = module.get_problem_html() + # Try to render the block with DEBUG turned on + html = block.get_problem_html() assert html is not None @@ -1782,11 +1781,11 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Run the test for each possible rerandomize value - module = CapaFactory.create(rerandomize=rerandomize) + block = CapaFactory.create(rerandomize=rerandomize) # Get the seed - # By this point, the module should have persisted the seed - seed = module.seed + # By this point, the block should have persisted the seed + seed = block.seed assert seed is not None # If we're not rerandomizing, the seed is always set @@ -1796,16 +1795,16 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Check the problem get_request_dict = {CapaFactory.input_key(): '3.14'} - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) # Expect that the seed is the same - assert seed == module.seed + assert seed == block.seed # Save the problem - module.save_problem(get_request_dict) + block.save_problem(get_request_dict) # Expect that the seed is the same - assert seed == module.seed + assert seed == block.seed @ddt.data( 'false', @@ -1820,22 +1819,22 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss Run the test for each possible rerandomize value """ - def _reset_and_get_seed(module): + def _reset_and_get_seed(block): """ - Reset the XModule and return the module's seed + Reset the XBlock and return the block's seed """ # Simulate submitting an attempt # We need to do this, or reset_problem() will # fail because it won't re-randomize until the problem has been submitted # the problem yet. - module.done = True + block.done = True # Reset the problem - module.reset_problem({}) + block.reset_problem({}) # Return the seed - return module.seed + return block.seed def _retry_and_check(num_tries, test_func): ''' @@ -1852,11 +1851,11 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss break return success - module = CapaFactory.create(rerandomize=rerandomize, done=True) + block = CapaFactory.create(rerandomize=rerandomize, done=True) # Get the seed - # By this point, the module should have persisted the seed - seed = module.seed + # By this point, the block should have persisted the seed + seed = block.seed assert seed is not None # We do NOT want the seed to reset if rerandomize @@ -1866,7 +1865,7 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss if rerandomize in [RANDOMIZATION.NEVER, 'false', RANDOMIZATION.PER_STUDENT]: - assert seed == _reset_and_get_seed(module) + assert seed == _reset_and_get_seed(block) # Otherwise, we expect the seed to change # to another valid seed @@ -1875,9 +1874,9 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Since there's a small chance (expected) we might get the # same seed again, give it 10 chances # to generate a different seed - success = _retry_and_check(10, lambda: _reset_and_get_seed(module) != seed) + success = _retry_and_check(10, lambda: _reset_and_get_seed(block) != seed) - assert module.seed is not None + assert block.seed is not None msg = 'Could not get a new seed from reset after 10 tries' assert success, msg @@ -1894,27 +1893,27 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss Run the test for each possible rerandomize value """ - def _reset_and_get_seed(module): + def _reset_and_get_seed(block): """ - Reset the XModule and return the module's seed + Reset the XBlock and return the block's seed """ # Reset the problem # By default, the problem is instantiated as unsubmitted - module.reset_problem({}) + block.reset_problem({}) # Return the seed - return module.seed + return block.seed - module = CapaFactory.create(rerandomize=rerandomize, done=False) + block = CapaFactory.create(rerandomize=rerandomize, done=False) # Get the seed - # By this point, the module should have persisted the seed - seed = module.seed + # By this point, the block should have persisted the seed + seed = block.seed assert seed is not None # the seed should never change because the student hasn't finished the problem - assert seed == _reset_and_get_seed(module) + assert seed == _reset_and_get_seed(block) @ddt.data( RANDOMIZATION.ALWAYS, @@ -1927,8 +1926,8 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss # Get a bunch of seeds, they should all be in 0-999. i = 200 while i > 0: - module = CapaFactory.create(rerandomize=rerandomize) - assert 0 <= module.seed < 1000 + block = CapaFactory.create(rerandomize=rerandomize) + assert 0 <= block.seed < 1000 i -= 1 @patch('xmodule.capa_block.log') @@ -1940,8 +1939,8 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss error_types = [TypeError, ValueError] for error_type in error_types: mock_progress.side_effect = error_type - module = CapaFactory.create() - assert module.get_progress() is None + block = CapaFactory.create() + assert block.get_progress() is None mock_log.exception.assert_called_once_with('Got bad progress') mock_log.reset_mock() @@ -1951,9 +1950,9 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss Check that if the weight is 0 get_progress does not try to create a Progress object. """ mock_progress.return_value = True - module = CapaFactory.create() - module.weight = 0 - progress = module.get_progress() + block = CapaFactory.create() + block.weight = 0 + progress = block.get_progress() assert progress is None assert not mock_progress.called @@ -1962,14 +1961,14 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ Check that score and total are calculated correctly for the progress fraction. """ - module = CapaFactory.create() - module.weight = 1 - module.get_progress() + block = CapaFactory.create() + block.weight = 1 + block.get_progress() mock_progress.assert_called_with(0, 1) - other_module = CapaFactory.create(correct=True) - other_module.weight = 1 - other_module.get_progress() + other_block = CapaFactory.create(correct=True) + other_block.weight = 1 + other_block.get_progress() mock_progress.assert_called_with(1, 1) @ddt.data( @@ -1985,11 +1984,11 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ Check that score and total are calculated correctly for the progress fraction. """ - module = CapaFactory.create(correct=is_correct, - show_correctness=show_correctness, - due=self.tomorrow_str) - module.weight = 1 - score, total = module.get_display_progress() + block = CapaFactory.create(correct=is_correct, + show_correctness=show_correctness, + due=self.tomorrow_str) + block.weight = 1 + score, total = block.get_display_progress() assert score == expected_score assert total == 1 @@ -1997,17 +1996,17 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ Check that get_html() calls get_progress() with no arguments. """ - module = CapaFactory.create() - module.get_progress = Mock(wraps=module.get_progress) - module.get_html() - module.get_progress.assert_called_with() + block = CapaFactory.create() + block.get_progress = Mock(wraps=block.get_progress) + block.get_html() + block.get_progress.assert_called_with() def test_get_problem(self): """ Check that get_problem() returns the expected dictionary. """ - module = CapaFactory.create() - assert module.get_problem('data') == {'html': module.get_problem_html(encapsulate=False)} + block = CapaFactory.create() + assert block.get_problem('data') == {'html': block.get_problem_html(encapsulate=False)} # Standard question with shuffle="true" used by a few tests common_shuffle_xml = textwrap.dedent(""" @@ -2028,10 +2027,10 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss Check that shuffle unmasking is plumbed through: when submit_problem is called, unmasked names should appear in the publish event_info. """ - module = CapaFactory.create(xml=self.common_shuffle_xml) - with patch.object(module.runtime, 'publish') as mock_publish: + block = CapaFactory.create(xml=self.common_shuffle_xml) + with patch.object(block.runtime, 'publish') as mock_publish: get_request_dict = {CapaFactory.input_key(): 'choice_3'} # the correct choice - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) mock_call = mock_publish.mock_calls[1] event_info = mock_call[1][2] assert event_info['answers'][CapaFactory.answer_key()] == 'choice_3' @@ -2043,10 +2042,10 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss @unittest.skip("masking temporarily disabled") def test_save_unmask(self): """On problem save, unmasked data should appear on publish.""" - module = CapaFactory.create(xml=self.common_shuffle_xml) - with patch.object(module.runtime, 'publish') as mock_publish: + block = CapaFactory.create(xml=self.common_shuffle_xml) + with patch.object(block.runtime, 'publish') as mock_publish: get_request_dict = {CapaFactory.input_key(): 'mask_0'} - module.save_problem(get_request_dict) + block.save_problem(get_request_dict) mock_call = mock_publish.mock_calls[0] event_info = mock_call[1][1] assert event_info['answers'][CapaFactory.answer_key()] == 'choice_2' @@ -2055,12 +2054,12 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss @unittest.skip("masking temporarily disabled") def test_reset_unmask(self): """On problem reset, unmask names should appear publish.""" - module = CapaFactory.create(xml=self.common_shuffle_xml) + block = CapaFactory.create(xml=self.common_shuffle_xml) get_request_dict = {CapaFactory.input_key(): 'mask_0'} - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) # On reset, 'old_state' should use unmasked names - with patch.object(module.runtime, 'publish') as mock_publish: - module.reset_problem(None) + with patch.object(block.runtime, 'publish') as mock_publish: + block.reset_problem(None) mock_call = mock_publish.mock_calls[0] event_info = mock_call[1][1] assert mock_call[1][0] == 'reset_problem' @@ -2070,12 +2069,12 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss @unittest.skip("masking temporarily disabled") def test_rescore_unmask(self): """On problem rescore, unmasked names should appear on publish.""" - module = CapaFactory.create(xml=self.common_shuffle_xml) + block = CapaFactory.create(xml=self.common_shuffle_xml) get_request_dict = {CapaFactory.input_key(): 'mask_0'} - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) # On rescore, state/student_answers should use unmasked names - with patch.object(module.runtime, 'publish') as mock_publish: - module.rescore_problem(only_if_higher=False) # lint-amnesty, pylint: disable=no-member + with patch.object(block.runtime, 'publish') as mock_publish: + block.rescore_problem(only_if_higher=False) # lint-amnesty, pylint: disable=no-member mock_call = mock_publish.mock_calls[0] event_info = mock_call[1][1] assert mock_call[1][0] == 'problem_rescore' @@ -2096,10 +2095,10 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """) - module = CapaFactory.create(xml=xml) - with patch.object(module.runtime, 'publish') as mock_publish: + block = CapaFactory.create(xml=xml) + with patch.object(block.runtime, 'publish') as mock_publish: get_request_dict = {CapaFactory.input_key(): 'choice_2'} # mask_X form when masking enabled - module.submit_problem(get_request_dict) + block.submit_problem(get_request_dict) mock_call = mock_publish.mock_calls[1] event_info = mock_call[1][2] assert event_info['answers'][CapaFactory.answer_key()] == 'choice_2' @@ -2119,8 +2118,8 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss """ Verify that display_name_with_default works as expected. """ - module = CapaFactory.create(display_name=display_name) - assert module.display_name_with_default == expected_display_name + block = CapaFactory.create(display_name=display_name) + assert block.display_name_with_default == expected_display_name @ddt.data( '', @@ -2131,11 +2130,11 @@ class ProblemBlockTest(unittest.TestCase): # lint-amnesty, pylint: disable=miss Verify that if problem display name is not provided then a default name is used. """ render_template = Mock(return_value="
    Test Template HTML
    ") - module = CapaFactory.create(display_name=display_name, render_template=render_template) - module.get_problem_html() + block = CapaFactory.create(display_name=display_name, render_template=render_template) + block.get_problem_html() render_args, _ = render_template.call_args context = render_args[1] - assert context['problem']['name'] == module.location.block_type + assert context['problem']['name'] == block.location.block_type @ddt.ddt @@ -2941,14 +2940,14 @@ class ProblemCheckTrackingTest(unittest.TestCase): # Whitespace screws up comparisons xml = ''.join(line.strip() for line in xml.split('\n')) factory = self.capa_factory_for_problem_xml(xml) - module = factory.create() + block = factory.create() answer_input_dict = { factory.input_key(2): 'blue', factory.input_key(3): 'choice_0', factory.input_key(4): ['choice_0', 'choice_1'], } - event = self.get_event_for_answers(module, answer_input_dict) + event = self.get_event_for_answers(block, answer_input_dict) assert event['submission'] ==\ {factory.answer_key(2): {'question': 'What color is the open ocean on a sunny day?', @@ -2981,9 +2980,9 @@ class ProblemCheckTrackingTest(unittest.TestCase): return CustomCapaFactory - def get_event_for_answers(self, module, answer_input_dict): # lint-amnesty, pylint: disable=missing-function-docstring - with patch.object(module.runtime, 'publish') as mock_publish: - module.submit_problem(answer_input_dict) + def get_event_for_answers(self, block, answer_input_dict): # lint-amnesty, pylint: disable=missing-function-docstring + with patch.object(block.runtime, 'publish') as mock_publish: + block.submit_problem(answer_input_dict) assert len(mock_publish.mock_calls) >= 2 # There are potentially 2 track logs: answers and hint. [-1]=answers. @@ -2994,13 +2993,13 @@ class ProblemCheckTrackingTest(unittest.TestCase): def test_numerical_textline(self): factory = CapaFactory - module = factory.create() + block = factory.create() answer_input_dict = { factory.input_key(2): '3.14' } - event = self.get_event_for_answers(module, answer_input_dict) + event = self.get_event_for_answers(block, answer_input_dict) assert event['submission'] ==\ {factory.answer_key(2): {'question': '', 'answer': '3.14', 'response_type': 'numericalresponse', @@ -3022,13 +3021,13 @@ class ProblemCheckTrackingTest(unittest.TestCase): """.format(group_label, input1_label, input2_label)) - module = factory.create() + block = factory.create() answer_input_dict = { factory.input_key(2, 1): 'blue', factory.input_key(2, 2): 'yellow', } - event = self.get_event_for_answers(module, answer_input_dict) + event = self.get_event_for_answers(block, answer_input_dict) assert event['submission'] ==\ {factory.answer_key(2, 1): {'group_label': group_label, 'question': input1_label, @@ -3084,14 +3083,14 @@ class ProblemCheckTrackingTest(unittest.TestCase): """.format(group_label, input1_label, input2_label)) - module = factory.create() + block = factory.create() answer_input_dict = { factory.input_key(2, 1): 'apple', factory.input_key(2, 2): 'cucumber', } - event = self.get_event_for_answers(module, answer_input_dict) + event = self.get_event_for_answers(block, answer_input_dict) assert event['submission'] ==\ {factory.answer_key(2, 1): {'group_label': group_label, 'question': input1_label, @@ -3108,13 +3107,13 @@ class ProblemCheckTrackingTest(unittest.TestCase): def test_rerandomized_inputs(self): factory = CapaFactory - module = factory.create(rerandomize=RANDOMIZATION.ALWAYS) + block = factory.create(rerandomize=RANDOMIZATION.ALWAYS) answer_input_dict = { factory.input_key(2): '3.14' } - event = self.get_event_for_answers(module, answer_input_dict) + event = self.get_event_for_answers(block, answer_input_dict) assert event['submission'] ==\ {factory.answer_key(2): {'question': '', 'answer': '3.14', @@ -3122,7 +3121,7 @@ class ProblemCheckTrackingTest(unittest.TestCase): 'input_type': 'textline', 'correct': True, 'group_label': '', - 'variant': module.seed}} + 'variant': block.seed}} @patch.object(XQueueInterface, '_http_post') def test_file_inputs(self, mock_xqueue_post): @@ -3133,7 +3132,7 @@ class ProblemCheckTrackingTest(unittest.TestCase): self.addCleanup(fileobj.close) factory = CapaFactoryWithFiles - module = factory.create() + block = factory.create() # Mock the XQueueInterface post method mock_xqueue_post.return_value = (0, "ok") @@ -3143,7 +3142,7 @@ class ProblemCheckTrackingTest(unittest.TestCase): CapaFactoryWithFiles.input_key(response_num=3): 'None', } - event = self.get_event_for_answers(module, answer_input_dict) + event = self.get_event_for_answers(block, answer_input_dict) assert event['submission'] ==\ {factory.answer_key(2): {'question': '', 'answer': fpaths, diff --git a/xmodule/tests/test_conditional.py b/xmodule/tests/test_conditional.py index 4355612b96..b36ae92b63 100644 --- a/xmodule/tests/test_conditional.py +++ b/xmodule/tests/test_conditional.py @@ -29,16 +29,16 @@ COURSE = 'conditional' # name of directory with course data class DummySystem(ImportSystem): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring @patch('xmodule.modulestore.xml.OSFS', lambda directory: MemoryFS()) - def __init__(self, load_error_modules): + def __init__(self, load_error_blocks): - xmlstore = XMLModuleStore("data_dir", source_dirs=[], load_error_modules=load_error_modules) + xmlstore = XMLModuleStore("data_dir", source_dirs=[], load_error_blocks=load_error_blocks) super().__init__( xmlstore=xmlstore, course_id=CourseKey.from_string('/'.join([ORG, COURSE, 'test_run'])), course_dir='test_dir', error_tracker=Mock(), - load_error_modules=load_error_modules, + load_error_blocks=load_error_blocks, ) def render_template(self, template, context): # lint-amnesty, pylint: disable=method-hidden @@ -58,20 +58,20 @@ class ConditionalFactory: to allow for testing. """ @staticmethod - def create(system, source_is_error_module=False, source_visible_to_staff_only=False): + def create(system, source_is_error_block=False, source_visible_to_staff_only=False): """ - return a dict of modules: the conditional with a single source and a single child. - Keys are 'cond_module', 'source_module', and 'child_module'. + return a dict of blocks: the conditional with a single source and a single child. + Keys are 'cond_block', 'source_block', and 'child_block'. - if the source_is_error_module flag is set, create a real ErrorBlock for the source. + if the source_is_error_block flag is set, create a real ErrorBlock for the source. """ descriptor_system = get_test_descriptor_system() # construct source descriptor and module: source_location = BlockUsageLocator(CourseLocator("edX", "conditional_test", "test_run", deprecated=True), "problem", "SampleProblem", deprecated=True) - if source_is_error_module: - # Make an error descriptor and module + if source_is_error_block: + # Make an error descriptor and block source_descriptor = ErrorBlock.from_xml( 'some random xml data', system, @@ -136,9 +136,9 @@ class ConditionalFactory: ] # return dict: - return {'cond_module': cond_descriptor, - 'source_module': source_descriptor, - 'child_module': child_descriptor} + return {'cond_block': cond_descriptor, + 'source_block': source_descriptor, + 'child_block': child_descriptor} class ConditionalBlockBasicTest(unittest.TestCase): @@ -153,38 +153,38 @@ class ConditionalBlockBasicTest(unittest.TestCase): def test_icon_class(self): '''verify that get_icon_class works independent of condition satisfaction''' - modules = ConditionalFactory.create(self.test_system) + blocks = ConditionalFactory.create(self.test_system) for attempted in ["false", "true"]: for icon_class in ['other', 'problem', 'video']: - modules['source_module'].is_attempted = attempted - modules['child_module'].get_icon_class = lambda: icon_class # lint-amnesty, pylint: disable=cell-var-from-loop - assert modules['cond_module'].get_icon_class() == icon_class + blocks['source_block'].is_attempted = attempted + blocks['child_block'].get_icon_class = lambda: icon_class # lint-amnesty, pylint: disable=cell-var-from-loop + assert blocks['cond_block'].get_icon_class() == icon_class def test_get_html(self): - modules = ConditionalFactory.create(self.test_system) + blocks = ConditionalFactory.create(self.test_system) # because get_test_system returns the repr of the context dict passed to render_template, # we reverse it here - html = modules['cond_module'].render(STUDENT_VIEW).content - mako_service = modules['cond_module'].xmodule_runtime.service(modules['cond_module'], 'mako') + html = blocks['cond_block'].render(STUDENT_VIEW).content + mako_service = blocks['cond_block'].xmodule_runtime.service(blocks['cond_block'], 'mako') expected = mako_service.render_template('conditional_ajax.html', { - 'ajax_url': modules['cond_module'].ajax_url, + 'ajax_url': blocks['cond_block'].ajax_url, 'element_id': 'i4x-edX-conditional_test-conditional-SampleConditional', 'depends': 'i4x-edX-conditional_test-problem-SampleProblem', }) assert expected == html def test_handle_ajax(self): - modules = ConditionalFactory.create(self.test_system) - modules['cond_module'].save() - modules['source_module'].is_attempted = "false" - ajax = json.loads(modules['cond_module'].handle_ajax('', '')) + blocks = ConditionalFactory.create(self.test_system) + blocks['cond_block'].save() + blocks['source_block'].is_attempted = "false" + ajax = json.loads(blocks['cond_block'].handle_ajax('', '')) fragments = ajax['fragments'] assert not any(('This is a secret' in item['content']) for item in fragments) # now change state of the capa problem to make it completed - modules['source_module'].is_attempted = "true" - ajax = json.loads(modules['cond_module'].handle_ajax('', '')) - modules['cond_module'].save() + blocks['source_block'].is_attempted = "true" + ajax = json.loads(blocks['cond_block'].handle_ajax('', '')) + blocks['cond_block'].save() fragments = ajax['fragments'] assert any(('This is a secret' in item['content']) for item in fragments) @@ -193,24 +193,24 @@ class ConditionalBlockBasicTest(unittest.TestCase): Check that handle_ajax works properly if the source is really an ErrorBlock, and that the condition is not satisfied. ''' - modules = ConditionalFactory.create(self.test_system, source_is_error_module=True) - modules['cond_module'].save() - ajax = json.loads(modules['cond_module'].handle_ajax('', '')) + blocks = ConditionalFactory.create(self.test_system, source_is_error_block=True) + blocks['cond_block'].save() + ajax = json.loads(blocks['cond_block'].handle_ajax('', '')) fragments = ajax['fragments'] assert not any(('This is a secret' in item['content']) for item in fragments) @patch('xmodule.conditional_block.log') - def test_conditional_with_staff_only_source_module(self, mock_log): - modules = ConditionalFactory.create( + def test_conditional_with_staff_only_source_block(self, mock_log): + blocks = ConditionalFactory.create( self.test_system, source_visible_to_staff_only=True, ) - cond_module = modules['cond_module'] - cond_module.save() - cond_module.is_attempted = "false" - cond_module.handle_ajax('', '') + cond_block = blocks['cond_block'] + cond_block.save() + cond_block.is_attempted = "false" + cond_block.handle_ajax('', '') assert not mock_log.warn.called - assert None in cond_module.get_required_blocks + assert None in cond_block.get_required_blocks class ConditionalBlockXmlTest(unittest.TestCase): @@ -226,7 +226,7 @@ class ConditionalBlockXmlTest(unittest.TestCase): assert len(courses) == 1 self.course = courses[0] - def get_module_for_location(self, location): + def get_block_for_location(self, location): descriptor = self.modulestore.get_item(location, depth=None) return self.test_system.get_block_for_descriptor(descriptor) @@ -239,9 +239,9 @@ class ConditionalBlockXmlTest(unittest.TestCase): location = BlockUsageLocator(CourseLocator("HarvardX", "ER22x", "2013_Spring", deprecated=True), "conditional", "condone", deprecated=True) - module = self.get_module_for_location(location) - html = module.render(STUDENT_VIEW).content - mako_service = module.xmodule_runtime.service(module, 'mako') + block = self.get_block_for_location(location) + html = block.render(STUDENT_VIEW).content + mako_service = block.xmodule_runtime.service(block, 'mako') html_expect = mako_service.render_template( 'conditional_ajax.html', { @@ -253,17 +253,17 @@ class ConditionalBlockXmlTest(unittest.TestCase): ) assert html == html_expect - ajax = json.loads(module.handle_ajax('', '')) + ajax = json.loads(block.handle_ajax('', '')) fragments = ajax['fragments'] assert not any(('This is a secret' in item['content']) for item in fragments) # Now change state of the capa problem to make it completed - inner_module = self.get_module_for_location(location.replace(category="problem", name='choiceprob')) - inner_module.attempts = 1 + inner_block = self.get_block_for_location(location.replace(category="problem", name='choiceprob')) + inner_block.attempts = 1 # Save our modifications to the underlying KeyValueStore so they can be persisted - inner_module.save() + inner_block.save() - ajax = json.loads(module.handle_ajax('', '')) + ajax = json.loads(block.handle_ajax('', '')) fragments = ajax['fragments'] assert any(('This is a secret' in item['content']) for item in fragments) @@ -323,15 +323,15 @@ class ConditionalBlockXmlTest(unittest.TestCase): assert definition == expected_definition def test_presence_attributes_in_xml_attributes(self): - modules = ConditionalFactory.create(self.test_system) - modules['cond_module'].save() - modules['cond_module'].definition_to_xml(Mock()) + blocks = ConditionalFactory.create(self.test_system) + blocks['cond_block'].save() + blocks['cond_block'].definition_to_xml(Mock()) expected_xml_attributes = { 'attempted': 'true', 'message': 'You must complete {link} before you can access this unit.', 'sources': '' } - self.assertDictEqual(modules['cond_module'].xml_attributes, expected_xml_attributes) + self.assertDictEqual(blocks['cond_block'].xml_attributes, expected_xml_attributes) class ConditionalBlockStudioTest(XModuleXmlImportTest): diff --git a/xmodule/tests/test_course_block.py b/xmodule/tests/test_course_block.py index 8c032dc0bb..183a4f9c06 100644 --- a/xmodule/tests/test_course_block.py +++ b/xmodule/tests/test_course_block.py @@ -40,10 +40,10 @@ class CourseFieldsTestCase(unittest.TestCase): class DummySystem(ImportSystem): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring @patch('xmodule.modulestore.xml.OSFS', lambda dir: MemoryFS()) - def __init__(self, load_error_modules, course_id=None): + def __init__(self, load_error_blocks, course_id=None): xmlstore = XMLModuleStore("data_dir", source_dirs=[], - load_error_modules=load_error_modules) + load_error_blocks=load_error_blocks) if course_id is None: course_id = CourseKey.from_string('/'.join([ORG, COURSE, 'test_run'])) course_dir = "test_dir" @@ -54,7 +54,7 @@ class DummySystem(ImportSystem): # lint-amnesty, pylint: disable=abstract-metho course_id=course_id, course_dir=course_dir, error_tracker=error_tracker, - load_error_modules=load_error_modules, + load_error_blocks=load_error_blocks, services={'field-data': KvsFieldData(DictKeyValueStore())}, ) @@ -69,7 +69,7 @@ def get_dummy_course( ): """Get a dummy course""" - system = DummySystem(load_error_modules=True) + system = DummySystem(load_error_blocks=True) def to_attrb(n, v): return '' if v is None else f'{n}="{v}"'.lower() @@ -112,7 +112,7 @@ class HasEndedMayCertifyTestCase(unittest.TestCase): def setUp(self): super().setUp() - system = DummySystem(load_error_modules=True) # lint-amnesty, pylint: disable=unused-variable + system = DummySystem(load_error_blocks=True) # lint-amnesty, pylint: disable=unused-variable past_end = (datetime.now() - timedelta(days=12)).strftime("%Y-%m-%dT%H:%M:00") future_end = (datetime.now() + timedelta(days=12)).strftime("%Y-%m-%dT%H:%M:00") diff --git a/xmodule/tests/test_delay_between_attempts.py b/xmodule/tests/test_delay_between_attempts.py index 871156665a..9b1c58d8aa 100644 --- a/xmodule/tests/test_delay_between_attempts.py +++ b/xmodule/tests/test_delay_between_attempts.py @@ -28,7 +28,7 @@ from . import get_test_system class CapaFactoryWithDelay: """ - Create problem modules class, specialized for delay_between_attempts + Create problem blocks class, specialized for delay_between_attempts test cases. This factory seems different enough from the one in test_capa_block that unifying them is unattractive. Removed the unused optional arguments. @@ -104,7 +104,7 @@ class CapaFactoryWithDelay: field_data['attempts'] = int(attempts) system = get_test_system(render_template=Mock(return_value="
    Test Template HTML
    ")) - module = ProblemBlock( + block = ProblemBlock( system, DictFieldData(field_data), ScopeIds(None, None, location, location), @@ -112,11 +112,11 @@ class CapaFactoryWithDelay: if correct: # Could set the internal state formally, but here we just jam in the score. - module.score = Score(raw_earned=1, raw_possible=1) + block.score = Score(raw_earned=1, raw_possible=1) else: - module.score = Score(raw_earned=0, raw_possible=1) + block.score = Score(raw_earned=0, raw_possible=1) - return module + return block class XModuleQuizAttemptsDelayTest(unittest.TestCase): @@ -131,37 +131,37 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): considered_now=None, skip_submit_problem=False): """Unified create and check code for the tests here.""" - module = CapaFactoryWithDelay.create( + block = CapaFactoryWithDelay.create( attempts=num_attempts, max_attempts=99, last_submission_time=last_submission_time, submission_wait_seconds=submission_wait_seconds ) - module.done = False + block.done = False get_request_dict = {CapaFactoryWithDelay.input_key(): "3.14"} if skip_submit_problem: - return (module, None) + return (block, None) if considered_now is not None: - result = module.submit_problem(get_request_dict, considered_now) + result = block.submit_problem(get_request_dict, considered_now) else: - result = module.submit_problem(get_request_dict) - return (module, result) + result = block.submit_problem(get_request_dict) + return (block, result) def test_first_submission(self): # Not attempted yet num_attempts = 0 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=None ) # Successfully submitted and answered # Also, the number of attempts should increment by 1 assert result['success'] == 'correct' - assert module.attempts == (num_attempts + 1) + assert block.attempts == (num_attempts + 1) def test_no_wait_time(self): num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime.now(UTC), submission_wait_seconds=0 @@ -169,12 +169,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # Successfully submitted and answered # Also, the number of attempts should increment by 1 assert result['success'] == 'correct' - assert module.attempts == (num_attempts + 1) + assert block.attempts == (num_attempts + 1) def test_submit_quiz_in_rapid_succession(self): # Already attempted once (just now) and thus has a submitted time num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime.now(UTC), submission_wait_seconds=123 @@ -182,12 +182,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # You should get a dialog that tells you to wait # Also, the number of attempts should not be incremented self.assertRegex(result['success'], r"You must wait at least.*") - assert module.attempts == num_attempts + assert block.attempts == num_attempts def test_submit_quiz_too_soon(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=180, @@ -196,12 +196,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # You should get a dialog that tells you to wait 2 minutes # Also, the number of attempts should not be incremented self.assertRegex(result['success'], r"You must wait at least 3 minutes between submissions. 2 minutes remaining\..*") # lint-amnesty, pylint: disable=line-too-long - assert module.attempts == num_attempts + assert block.attempts == num_attempts def test_submit_quiz_1_second_too_soon(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=180, @@ -210,12 +210,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # You should get a dialog that tells you to wait 2 minutes # Also, the number of attempts should not be incremented self.assertRegex(result['success'], r"You must wait at least 3 minutes between submissions. 1 second remaining\..*") # lint-amnesty, pylint: disable=line-too-long - assert module.attempts == num_attempts + assert block.attempts == num_attempts def test_submit_quiz_as_soon_as_allowed(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=180, @@ -224,12 +224,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # Successfully submitted and answered # Also, the number of attempts should increment by 1 assert result['success'] == 'correct' - assert module.attempts == (num_attempts + 1) + assert block.attempts == (num_attempts + 1) def test_submit_quiz_after_delay_expired(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=180, @@ -238,14 +238,14 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # Successfully submitted and answered # Also, the number of attempts should increment by 1 assert result['success'] == 'correct' - assert module.attempts == (num_attempts + 1) + assert block.attempts == (num_attempts + 1) def test_still_cannot_submit_after_max_attempts(self): # Already attempted once (just now) and thus has a submitted time num_attempts = 99 # Regular create_and_check should fail with pytest.raises(xmodule.exceptions.NotFoundError): - (module, unused_result) = self.create_and_check( + (block, unused_result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=180, @@ -253,7 +253,7 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): ) # Now try it without the submit_problem - (module, unused_result) = self.create_and_check( + (block, unused_result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=180, @@ -261,12 +261,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): skip_submit_problem=True ) # Expect that number of attempts NOT incremented - assert module.attempts == num_attempts + assert block.attempts == num_attempts def test_submit_quiz_with_long_delay(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=60 * 60 * 2, @@ -275,12 +275,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # You should get a dialog that tells you to wait 2 minutes # Also, the number of attempts should not be incremented self.assertRegex(result['success'], r"You must wait at least 2 hours between submissions. 2 minutes 1 second remaining\..*") # lint-amnesty, pylint: disable=line-too-long - assert module.attempts == num_attempts + assert block.attempts == num_attempts def test_submit_quiz_with_involved_pretty_print(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=60 * 60 * 2 + 63, @@ -289,12 +289,12 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # You should get a dialog that tells you to wait 2 minutes # Also, the number of attempts should not be incremented self.assertRegex(result['success'], r"You must wait at least 2 hours 1 minute 3 seconds between submissions. 1 hour 2 minutes 59 seconds remaining\..*") # lint-amnesty, pylint: disable=line-too-long - assert module.attempts == num_attempts + assert block.attempts == num_attempts def test_submit_quiz_with_nonplural_pretty_print(self): # Already attempted once (just now) num_attempts = 1 - (module, result) = self.create_and_check( + (block, result) = self.create_and_check( num_attempts=num_attempts, last_submission_time=datetime.datetime(2013, 12, 6, 0, 17, 36, tzinfo=UTC), submission_wait_seconds=60, @@ -303,4 +303,4 @@ class XModuleQuizAttemptsDelayTest(unittest.TestCase): # You should get a dialog that tells you to wait 2 minutes # Also, the number of attempts should not be incremented self.assertRegex(result['success'], r"You must wait at least 1 minute between submissions. 1 minute remaining\..*") # lint-amnesty, pylint: disable=line-too-long - assert module.attempts == num_attempts + assert block.attempts == num_attempts diff --git a/xmodule/tests/test_export.py b/xmodule/tests/test_export.py index 56c00d0dc5..0e6469db70 100644 --- a/xmodule/tests/test_export.py +++ b/xmodule/tests/test_export.py @@ -140,7 +140,7 @@ class RoundTripTestCase(unittest.TestCase): list(second_import.modules[course_id].keys()) ) - print("Checking module equality") + print("Checking block equality") for location in initial_import.modules[course_id].keys(): print(("Checking", location)) assert blocks_are_equivalent(initial_import.modules[course_id][location], diff --git a/xmodule/tests/test_html_block.py b/xmodule/tests/test_html_block.py index 50968e54d7..df8c803b52 100644 --- a/xmodule/tests/test_html_block.py +++ b/xmodule/tests/test_html_block.py @@ -48,10 +48,10 @@ class HtmlBlockCourseApiTestCase(unittest.TestCase): """ field_data = DictFieldData({'data': '

    Some HTML

    '}) module_system = get_test_system() - module = HtmlBlock(module_system, field_data, Mock()) + block = HtmlBlock(module_system, field_data, Mock()) with override_settings(**settings): - assert module.student_view_data() ==\ + assert block.student_view_data() ==\ dict(enabled=False, message='To enable, set FEATURES["ENABLE_HTML_XBLOCK_STUDENT_VIEW_DATA"]') @ddt.data( @@ -76,8 +76,8 @@ class HtmlBlockCourseApiTestCase(unittest.TestCase): """ field_data = DictFieldData({'data': html}) module_system = get_test_system() - module = HtmlBlock(module_system, field_data, Mock()) - assert module.student_view_data() == dict(enabled=True, html=html) + block = HtmlBlock(module_system, field_data, Mock()) + assert block.student_view_data() == dict(enabled=True, html=html) @ddt.data( STUDENT_VIEW, @@ -90,8 +90,8 @@ class HtmlBlockCourseApiTestCase(unittest.TestCase): html = '

    This is a test

    ' field_data = DictFieldData({'data': html}) module_system = get_test_system() - module = HtmlBlock(module_system, field_data, Mock()) - rendered = module_system.render(module, view, {}).content + block = HtmlBlock(module_system, field_data, Mock()) + rendered = module_system.render(block, view, {}).content assert html in rendered @@ -101,14 +101,14 @@ class HtmlBlockSubstitutionTestCase(unittest.TestCase): # lint-amnesty, pylint: sample_xml = '''%%USER_ID%%''' field_data = DictFieldData({'data': sample_xml}) module_system = get_test_system() - module = HtmlBlock(module_system, field_data, Mock()) - assert module.get_html() == str(module_system.anonymous_student_id) + block = HtmlBlock(module_system, field_data, Mock()) + assert block.get_html() == str(module_system.anonymous_student_id) def test_substitution_course_id(self): sample_xml = '''%%COURSE_ID%%''' field_data = DictFieldData({'data': sample_xml}) module_system = get_test_system() - module = HtmlBlock(module_system, field_data, Mock()) + block = HtmlBlock(module_system, field_data, Mock()) course_key = CourseLocator( org='some_org', course='some_course', @@ -119,8 +119,8 @@ class HtmlBlockSubstitutionTestCase(unittest.TestCase): # lint-amnesty, pylint: block_type='problem', block_id='block_id' ) - module.scope_ids.usage_id = usage_key - assert module.get_html() == str(course_key) + block.scope_ids.usage_id = usage_key + assert block.get_html() == str(course_key) def test_substitution_without_magic_string(self): sample_xml = ''' @@ -130,15 +130,15 @@ class HtmlBlockSubstitutionTestCase(unittest.TestCase): # lint-amnesty, pylint: ''' field_data = DictFieldData({'data': sample_xml}) module_system = get_test_system() - module = HtmlBlock(module_system, field_data, Mock()) - assert module.get_html() == sample_xml + block = HtmlBlock(module_system, field_data, Mock()) + assert block.get_html() == sample_xml def test_substitution_without_anonymous_student_id(self): sample_xml = '''%%USER_ID%%''' field_data = DictFieldData({'data': sample_xml}) module_system = get_test_system(user=AnonymousUser()) - module = HtmlBlock(module_system, field_data, Mock()) - assert module.get_html() == sample_xml + block = HtmlBlock(module_system, field_data, Mock()) + assert block.get_html() == sample_xml class HtmlBlockIndexingTestCase(unittest.TestCase): @@ -229,7 +229,7 @@ class CourseInfoBlockTestCase(unittest.TestCase): def test_updates_render(self): """ - Tests that a course info module will render its updates, even if they are malformed. + Tests that a course info block will render its updates, even if they are malformed. """ sample_update_data = [ { @@ -246,7 +246,7 @@ class CourseInfoBlockTestCase(unittest.TestCase): ] ) ] - info_module = CourseInfoBlock( + info_block = CourseInfoBlock( get_test_system(), DictFieldData({'items': sample_update_data, 'data': ""}), Mock() @@ -254,13 +254,13 @@ class CourseInfoBlockTestCase(unittest.TestCase): # Prior to TNL-4115, an exception would be raised when trying to parse invalid dates in this method try: - info_module.get_html() + info_block.get_html() except ValueError: self.fail("CourseInfoBlock could not parse an invalid date!") def test_updates_order(self): """ - Tests that a course info module will render its updates in the correct order. + Tests that a course info block will render its updates in the correct order. """ sample_update_data = [ { @@ -282,7 +282,7 @@ class CourseInfoBlockTestCase(unittest.TestCase): "status": CourseInfoBlock.STATUS_VISIBLE, } ] - info_module = CourseInfoBlock( + info_block = CourseInfoBlock( Mock(), DictFieldData({'items': sample_update_data, 'data': ""}), Mock() @@ -312,10 +312,10 @@ class CourseInfoBlockTestCase(unittest.TestCase): ], 'hidden_updates': [], } - template_name = f"{info_module.TEMPLATE_DIR}/course_updates.html" - info_module.get_html() + template_name = f"{info_block.TEMPLATE_DIR}/course_updates.html" + info_block.get_html() # Assertion to validate that render function is called with the expected context - info_module.runtime.service(info_module, 'mako').render_template.assert_called_once_with( + info_block.runtime.service(info_block, 'mako').render_template.assert_called_once_with( template_name, expected_context ) diff --git a/xmodule/tests/test_import.py b/xmodule/tests/test_import.py index ece5dcab51..570b484ef0 100644 --- a/xmodule/tests/test_import.py +++ b/xmodule/tests/test_import.py @@ -32,12 +32,12 @@ RUN = 'test_run' class DummySystem(ImportSystem): # lint-amnesty, pylint: disable=abstract-method, missing-class-docstring @patch('xmodule.modulestore.xml.OSFS', lambda dir: OSFS(mkdtemp())) - def __init__(self, load_error_modules, library=False): + def __init__(self, load_error_blocks, library=False): if library: - xmlstore = LibraryXMLModuleStore("data_dir", source_dirs=[], load_error_modules=load_error_modules) + xmlstore = LibraryXMLModuleStore("data_dir", source_dirs=[], load_error_blocks=load_error_blocks) else: - xmlstore = XMLModuleStore("data_dir", source_dirs=[], load_error_modules=load_error_modules) + xmlstore = XMLModuleStore("data_dir", source_dirs=[], load_error_blocks=load_error_blocks) course_id = CourseKey.from_string('/'.join([ORG, COURSE, RUN])) course_dir = "test_dir" error_tracker = Mock() @@ -47,7 +47,7 @@ class DummySystem(ImportSystem): # lint-amnesty, pylint: disable=abstract-metho course_id=course_id, course_dir=course_dir, error_tracker=error_tracker, - load_error_modules=load_error_modules, + load_error_blocks=load_error_blocks, mixins=(InheritanceMixin, XModuleMixin), services={'field-data': KvsFieldData(DictKeyValueStore())}, ) @@ -57,12 +57,12 @@ class DummySystem(ImportSystem): # lint-amnesty, pylint: disable=abstract-metho class BaseCourseTestCase(TestCase): - '''Make sure module imports work properly, including for malformed inputs''' + '''Make sure block imports work properly, including for malformed inputs''' @staticmethod - def get_system(load_error_modules=True, library=False): + def get_system(load_error_blocks=True, library=False): '''Get a dummy system''' - return DummySystem(load_error_modules, library=library) + return DummySystem(load_error_blocks, library=library) def get_course(self, name): """Get a test course by directory name. If there's more than one, error.""" @@ -110,7 +110,7 @@ class PureXBlockImportTest(BaseCourseTestCase): ) @patch('xmodule.x_module.XModuleMixin.location') def test_parsing_pure_xblock(self, xml, mock_location): - system = self.get_system(load_error_modules=False) + system = self.get_system(load_error_blocks=False) descriptor = system.process_xml(xml) assert isinstance(descriptor, GenericXBlock) self.assert_xblocks_are_good(descriptor) @@ -488,7 +488,7 @@ class ImportTestCase(BaseCourseTestCase): # lint-amnesty, pylint: disable=missi def test_definition_loading(self): """When two courses share the same org and course name and - both have a module with the same url_name, the definitions shouldn't clash. + both have a block with the same url_name, the definitions shouldn't clash. TODO (vshnayder): once we have a CMS, this shouldn't happen--locations should uniquely name definitions. But in @@ -592,20 +592,20 @@ class ImportTestCase(BaseCourseTestCase): # lint-amnesty, pylint: disable=missi assert len(sections) == 1 conditional_location = course.id.make_usage_key('conditional', 'condone') - module = modulestore.get_item(conditional_location) - assert len(module.children) == 1 + block = modulestore.get_item(conditional_location) + assert len(block.children) == 1 poll_location = course.id.make_usage_key('poll_question', 'first_poll') - module = modulestore.get_item(poll_location) - assert len(module.get_children()) == 0 - assert module.voted is False - assert module.poll_answer == '' - assert module.poll_answers == {} - assert module.answers ==\ + block = modulestore.get_item(poll_location) + assert len(block.get_children()) == 0 + assert block.voted is False + assert block.poll_answer == '' + assert block.poll_answers == {} + assert block.answers ==\ [{'text': 'Yes', 'id': 'Yes'}, {'text': 'No', 'id': 'No'}, {'text': "Don't know", 'id': 'Dont_know'}] def test_error_on_import(self): - '''Check that when load_error_module is false, an exception is raised, rather than returning an ErrorBlock''' + '''Check that when load_error_block is false, an exception is raised, rather than returning an ErrorBlock''' bad_xml = '''''' system = self.get_system(False) @@ -623,10 +623,10 @@ class ImportTestCase(BaseCourseTestCase): # lint-amnesty, pylint: disable=missi assert len(sections) == 1 location = course.id.make_usage_key('word_cloud', 'cloud1') - module = modulestore.get_item(location) - assert len(module.get_children()) == 0 - assert module.num_inputs == 5 - assert module.num_top_words == 250 + block = modulestore.get_item(location) + assert len(block.get_children()) == 0 + assert block.num_inputs == 5 + assert block.num_top_words == 250 def test_cohort_config(self): """ diff --git a/xmodule/tests/test_library_content.py b/xmodule/tests/test_library_content.py index 616de330bb..30bbfdb117 100644 --- a/xmodule/tests/test_library_content.py +++ b/xmodule/tests/test_library_content.py @@ -54,24 +54,24 @@ class LibraryContentTest(MixedSplitTestCase): source_library_id=str(self.library.location.library_key) ) - def _bind_course_block(self, module): + def _bind_course_block(self, block): """ - Bind a module (part of self.course) so we can access student-specific data. + Bind a block (part of self.course) so we can access student-specific data. """ - module_system = get_test_system(course_id=module.location.course_key) - module_system.descriptor_runtime = module.runtime._descriptor_system # pylint: disable=protected-access + module_system = get_test_system(course_id=block.location.course_key) + module_system.descriptor_runtime = block.runtime._descriptor_system # pylint: disable=protected-access module_system._services['library_tools'] = self.tools # pylint: disable=protected-access def get_block(descriptor): """Mocks module_system get_block function""" - sub_module_system = get_test_system(course_id=module.location.course_key) + sub_module_system = get_test_system(course_id=block.location.course_key) sub_module_system.get_block_for_descriptor = get_block sub_module_system.descriptor_runtime = descriptor._runtime # pylint: disable=protected-access descriptor.bind_for_student(sub_module_system, self.user_id) return descriptor module_system.get_block_for_descriptor = get_block - module.xmodule_runtime = module_system + block.xmodule_runtime = module_system class TestLibraryContentExportImport(LibraryContentTest): @@ -102,7 +102,7 @@ class TestLibraryContentExportImport(LibraryContentTest): self.lc_block.runtime._descriptor_system.export_fs = self.export_fs # pylint: disable=protected-access # Prepare runtime for the import. - self.runtime = TestImportSystem(load_error_modules=True, course_id=self.lc_block.location.course_key) + self.runtime = TestImportSystem(load_error_blocks=True, course_id=self.lc_block.location.course_key) self.runtime.resources_fs = self.export_fs self.id_generator = Mock() @@ -207,7 +207,7 @@ class LibraryContentBlockTestMixin: # Normally the children get added when the "source_libraries" setting # is updated, but the way we do it through a factory doesn't do that. assert len(self.lc_block.children) == 0 - # Update the LibraryContent module: + # Update the LibraryContent block: self.lc_block.refresh_children() self.lc_block = self.store.get_item(self.lc_block.location) # Check that all blocks from the library are now children of the block: diff --git a/xmodule/tests/test_lti20_unit.py b/xmodule/tests/test_lti20_unit.py index 001c76965c..8923f4b474 100644 --- a/xmodule/tests/test_lti20_unit.py +++ b/xmodule/tests/test_lti20_unit.py @@ -29,10 +29,10 @@ class LTI20RESTResultServiceTest(unittest.TestCase): self.runtime.publish = Mock() self.runtime._services['rebind_user'] = Mock() # pylint: disable=protected-access - self.xmodule = LTIBlock(self.runtime, DictFieldData({}), Mock()) - self.lti_id = self.xmodule.lti_id - self.xmodule.due = None - self.xmodule.graceperiod = None + self.xblock = LTIBlock(self.runtime, DictFieldData({}), Mock()) + self.lti_id = self.xblock.lti_id + self.xblock.due = None + self.xblock.graceperiod = None def test_sanitize_get_context(self): """Tests that the get_context function does basic sanitization""" @@ -40,8 +40,8 @@ class LTI20RESTResultServiceTest(unittest.TestCase): mocked_course = Mock(name='mocked_course', lti_passports=['lti_id:test_client:test_secret']) modulestore = Mock(name='modulestore') modulestore.get_course.return_value = mocked_course - self.xmodule.runtime.modulestore = modulestore - self.xmodule.lti_id = "lti_id" + self.xblock.runtime.modulestore = modulestore + self.xblock.lti_id = "lti_id" test_cases = ( # (before sanitize, after sanitize) ("plaintext", "plaintext"), @@ -49,8 +49,8 @@ class LTI20RESTResultServiceTest(unittest.TestCase): ("bold 包", "bold 包"), # unicode, and tags pass through ) for case in test_cases: - self.xmodule.score_comment = case[0] - assert case[1] == self.xmodule.get_context()['comment'] + self.xblock.score_comment = case[0] + assert case[1] == self.xblock.get_context()['comment'] def test_lti20_rest_bad_contenttype(self): """ @@ -58,28 +58,28 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ with self.assertRaisesRegex(LTIError, "Content-Type must be"): request = Mock(headers={'Content-Type': 'Non-existent'}) - self.xmodule.verify_lti_2_0_result_rest_headers(request) + self.xblock.verify_lti_2_0_result_rest_headers(request) def test_lti20_rest_failed_oauth_body_verify(self): """ Input with bad oauth body hash verification """ err_msg = "OAuth body verification failed" - self.xmodule.verify_oauth_body_sign = Mock(side_effect=LTIError(err_msg)) + self.xblock.verify_oauth_body_sign = Mock(side_effect=LTIError(err_msg)) with self.assertRaisesRegex(LTIError, err_msg): request = Mock(headers={'Content-Type': 'application/vnd.ims.lis.v2.result+json'}) - self.xmodule.verify_lti_2_0_result_rest_headers(request) + self.xblock.verify_lti_2_0_result_rest_headers(request) def test_lti20_rest_good_headers(self): """ Input with good oauth body hash verification """ - self.xmodule.verify_oauth_body_sign = Mock(return_value=True) + self.xblock.verify_oauth_body_sign = Mock(return_value=True) request = Mock(headers={'Content-Type': 'application/vnd.ims.lis.v2.result+json'}) - self.xmodule.verify_lti_2_0_result_rest_headers(request) + self.xblock.verify_lti_2_0_result_rest_headers(request) # We just want the above call to complete without exceptions, and to have called verify_oauth_body_sign - assert self.xmodule.verify_oauth_body_sign.called + assert self.xblock.verify_oauth_body_sign.called BAD_DISPATCH_INPUTS = [ None, @@ -100,7 +100,7 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ for einput in self.BAD_DISPATCH_INPUTS: with self.assertRaisesRegex(LTIError, "No valid user id found in endpoint URL"): - self.xmodule.parse_lti_2_0_handler_suffix(einput) + self.xblock.parse_lti_2_0_handler_suffix(einput) GOOD_DISPATCH_INPUTS = [ ("user/abcd3", "abcd3"), @@ -113,7 +113,7 @@ class LTI20RESTResultServiceTest(unittest.TestCase): fit the form user/ """ for ginput, expected in self.GOOD_DISPATCH_INPUTS: - assert self.xmodule.parse_lti_2_0_handler_suffix(ginput) == expected + assert self.xblock.parse_lti_2_0_handler_suffix(ginput) == expected BAD_JSON_INPUTS = [ # (bad inputs, error message expected) @@ -161,7 +161,7 @@ class LTI20RESTResultServiceTest(unittest.TestCase): for error_inputs, error_message in self.BAD_JSON_INPUTS: for einput in error_inputs: with self.assertRaisesRegex(LTIError, error_message): - self.xmodule.parse_lti_2_0_result_json(einput) + self.xblock.parse_lti_2_0_result_json(einput) GOOD_JSON_INPUTS = [ (''' @@ -185,7 +185,7 @@ class LTI20RESTResultServiceTest(unittest.TestCase): Test the parsing of good comments """ for json_str, expected_comment in self.GOOD_JSON_INPUTS: - score, comment = self.xmodule.parse_lti_2_0_result_json(json_str) + score, comment = self.xblock.parse_lti_2_0_result_json(json_str) assert score == 0.1 assert comment == expected_comment @@ -226,30 +226,30 @@ class LTI20RESTResultServiceTest(unittest.TestCase): mock_request.body = body return mock_request - def setup_system_xmodule_mocks_for_lti20_request_test(self): + def setup_system_xblock_mocks_for_lti20_request_test(self): """ Helper fn to set up mocking for lti 2.0 request test """ - self.xmodule.max_score = Mock(return_value=1.0) - self.xmodule.get_client_key_secret = Mock(return_value=('test_client_key', 'test_client_secret')) - self.xmodule.verify_oauth_body_sign = Mock() + self.xblock.max_score = Mock(return_value=1.0) + self.xblock.get_client_key_secret = Mock(return_value=('test_client_key', 'test_client_secret')) + self.xblock.verify_oauth_body_sign = Mock() def test_lti20_put_like_delete_success(self): """ The happy path for LTI 2.0 PUT that acts like a delete """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() SCORE = 0.55 # pylint: disable=invalid-name COMMENT = "ಠ益ಠ" # pylint: disable=invalid-name - self.xmodule.module_score = SCORE - self.xmodule.score_comment = COMMENT + self.xblock.module_score = SCORE + self.xblock.score_comment = COMMENT mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT_LIKE_DELETE) # Now call the handler - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") # Now assert there's no score assert response.status_code == 200 - assert self.xmodule.module_score is None - assert self.xmodule.score_comment == '' + assert self.xblock.module_score is None + assert self.xblock.score_comment == '' (_, evt_type, called_grade_obj), _ = self.runtime.publish.call_args # pylint: disable=unpacking-non-sequence assert called_grade_obj ==\ {'user_id': self.USER_STANDIN.id, 'value': None, 'max_value': None, 'score_deleted': True} @@ -259,18 +259,18 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ The happy path for LTI 2.0 DELETE """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() SCORE = 0.55 # pylint: disable=invalid-name COMMENT = "ಠ益ಠ" # pylint: disable=invalid-name - self.xmodule.module_score = SCORE - self.xmodule.score_comment = COMMENT + self.xblock.module_score = SCORE + self.xblock.score_comment = COMMENT mock_request = self.get_signed_lti20_mock_request(b"", method='DELETE') # Now call the handler - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") # Now assert there's no score assert response.status_code == 200 - assert self.xmodule.module_score is None - assert self.xmodule.score_comment == '' + assert self.xblock.module_score is None + assert self.xblock.score_comment == '' (_, evt_type, called_grade_obj), _ = self.runtime.publish.call_args # pylint: disable=unpacking-non-sequence assert called_grade_obj ==\ {'user_id': self.USER_STANDIN.id, 'value': None, 'max_value': None, 'score_deleted': True} @@ -280,14 +280,14 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ The happy path for LTI 2.0 PUT that sets a score """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) # Now call the handler - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") # Now assert assert response.status_code == 200 - assert self.xmodule.module_score == 0.1 - assert self.xmodule.score_comment == 'ಠ益ಠ' + assert self.xblock.module_score == 0.1 + assert self.xblock.score_comment == 'ಠ益ಠ' (_, evt_type, called_grade_obj), _ = self.runtime.publish.call_args # pylint: disable=unpacking-non-sequence assert evt_type == 'grade' assert called_grade_obj ==\ @@ -297,10 +297,10 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ The happy path for LTI 2.0 GET when there's no score """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() mock_request = self.get_signed_lti20_mock_request(b"", method='GET') # Now call the handler - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") # Now assert assert response.status_code == 200 assert response.json == {'@context': 'http://purl.imsglobal.org/ctx/lis/v2/Result', '@type': 'Result'} @@ -309,14 +309,14 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ The happy path for LTI 2.0 GET when there is a score """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() SCORE = 0.55 # pylint: disable=invalid-name COMMENT = "ಠ益ಠ" # pylint: disable=invalid-name - self.xmodule.module_score = SCORE - self.xmodule.score_comment = COMMENT + self.xblock.module_score = SCORE + self.xblock.score_comment = COMMENT mock_request = self.get_signed_lti20_mock_request(b"", method='GET') # Now call the handler - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") # Now assert assert response.status_code == 200 assert response.json ==\ @@ -329,59 +329,59 @@ class LTI20RESTResultServiceTest(unittest.TestCase): """ Test we get a 404 when we don't GET or PUT """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) for bad_method in self.UNSUPPORTED_HTTP_METHODS: mock_request.method = bad_method - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") assert response.status_code == 404 def test_lti20_request_handler_bad_headers(self): """ Test that we get a 401 when header verification fails """ - self.setup_system_xmodule_mocks_for_lti20_request_test() - self.xmodule.verify_lti_2_0_result_rest_headers = Mock(side_effect=LTIError()) + self.setup_system_xblock_mocks_for_lti20_request_test() + self.xblock.verify_lti_2_0_result_rest_headers = Mock(side_effect=LTIError()) mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") assert response.status_code == 401 def test_lti20_request_handler_bad_dispatch_user(self): """ Test that we get a 404 when there's no (or badly formatted) user specified in the url """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, None) + response = self.xblock.lti_2_0_result_rest_handler(mock_request, None) assert response.status_code == 404 def test_lti20_request_handler_bad_json(self): """ Test that we get a 404 when json verification fails """ - self.setup_system_xmodule_mocks_for_lti20_request_test() - self.xmodule.parse_lti_2_0_result_json = Mock(side_effect=LTIError()) + self.setup_system_xblock_mocks_for_lti20_request_test() + self.xblock.parse_lti_2_0_result_json = Mock(side_effect=LTIError()) mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") assert response.status_code == 404 def test_lti20_request_handler_bad_user(self): """ Test that we get a 404 when the supplied user does not exist """ - self.setup_system_xmodule_mocks_for_lti20_request_test() + self.setup_system_xblock_mocks_for_lti20_request_test() self.runtime._services['user'] = StubUserService(user=None) # pylint: disable=protected-access mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") assert response.status_code == 404 def test_lti20_request_handler_grade_past_due(self): """ Test that we get a 404 when accept_grades_past_due is False and it is past due """ - self.setup_system_xmodule_mocks_for_lti20_request_test() - self.xmodule.due = datetime.datetime.now(UTC) - self.xmodule.accept_grades_past_due = False + self.setup_system_xblock_mocks_for_lti20_request_test() + self.xblock.due = datetime.datetime.now(UTC) + self.xblock.accept_grades_past_due = False mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT) - response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd") + response = self.xblock.lti_2_0_result_rest_handler(mock_request, "user/abcd") assert response.status_code == 404 diff --git a/xmodule/tests/test_lti_unit.py b/xmodule/tests/test_lti_unit.py index 8bd0db9db8..47d480d5bf 100644 --- a/xmodule/tests/test_lti_unit.py +++ b/xmodule/tests/test_lti_unit.py @@ -67,14 +67,14 @@ class LTIBlockTest(TestCase): self.system.publish = Mock() self.system._services['rebind_user'] = Mock() # pylint: disable=protected-access - self.xmodule = LTIBlock( + self.xblock = LTIBlock( self.system, DictFieldData({}), ScopeIds(None, None, None, BlockUsageLocator(self.course_id, 'lti', 'name')) ) - current_user = self.system.service(self.xmodule, 'user').get_current_user() + current_user = self.system.service(self.xblock, 'user').get_current_user() self.user_id = current_user.opt_attrs.get(ATTR_KEY_ANONYMOUS_USER_ID) - self.lti_id = self.xmodule.lti_id + self.lti_id = self.xblock.lti_id self.unquoted_resource_link_id = '{}-i4x-2-3-lti-31de800015cf4afb973356dbe81496df'.format( settings.LMS_BASE @@ -90,8 +90,8 @@ class LTIBlockTest(TestCase): 'messageIdentifier': '528243ba5241b', } - self.xmodule.due = None - self.xmodule.graceperiod = None + self.xblock.due = None + self.xblock.graceperiod = None def get_request_body(self, params=None): """Fetches the body of a request specified by params""" @@ -138,7 +138,7 @@ class LTIBlockTest(TestCase): """ request = Request(self.environ) request.body = self.get_request_body() - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) expected_response = { 'action': None, @@ -163,7 +163,7 @@ class LTIBlockTest(TestCase): request = Request(self.environ) request.authorization = "bad authorization header" request.body = self.get_request_body() - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) expected_response = { 'action': None, @@ -179,11 +179,11 @@ class LTIBlockTest(TestCase): If we have no real user, we should send back failure response. """ self.system._services['user'] = StubUserService(user=None) # pylint: disable=protected-access - self.xmodule.verify_oauth_body_sign = Mock() - self.xmodule.has_score = True + self.xblock.verify_oauth_body_sign = Mock() + self.xblock.has_score = True request = Request(self.environ) request.body = self.get_request_body() - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) expected_response = { 'action': None, @@ -198,12 +198,12 @@ class LTIBlockTest(TestCase): """ Should fail if we do not accept past due grades, and it is past due. """ - self.xmodule.accept_grades_past_due = False - self.xmodule.due = datetime.datetime.now(UTC) - self.xmodule.graceperiod = Timedelta().from_json("0 seconds") + self.xblock.accept_grades_past_due = False + self.xblock.due = datetime.datetime.now(UTC) + self.xblock.graceperiod = Timedelta().from_json("0 seconds") request = Request(self.environ) request.body = self.get_request_body() - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) expected_response = { 'action': None, @@ -218,10 +218,10 @@ class LTIBlockTest(TestCase): """ Grade returned from Tool Provider is outside the range 0.0-1.0. """ - self.xmodule.verify_oauth_body_sign = Mock() + self.xblock.verify_oauth_body_sign = Mock() request = Request(self.environ) request.body = self.get_request_body(params={'grade': '10'}) - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) expected_response = { 'action': None, @@ -236,10 +236,10 @@ class LTIBlockTest(TestCase): """ Grade returned from Tool Provider doesn't use a period as the decimal point. """ - self.xmodule.verify_oauth_body_sign = Mock() + self.xblock.verify_oauth_body_sign = Mock() request = Request(self.environ) request.body = self.get_request_body(params={'grade': '0,5'}) - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) msg = "could not convert string to float: '0,5'" expected_response = { @@ -256,10 +256,10 @@ class LTIBlockTest(TestCase): Action returned from Tool Provider isn't supported. `replaceResultRequest` is supported only. """ - self.xmodule.verify_oauth_body_sign = Mock() + self.xblock.verify_oauth_body_sign = Mock() request = Request(self.environ) request.body = self.get_request_body({'action': 'wrongAction'}) - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') real_response = self.get_response_values(response) expected_response = { 'action': None, @@ -274,11 +274,11 @@ class LTIBlockTest(TestCase): """ Response from Tool Provider is correct. """ - self.xmodule.verify_oauth_body_sign = Mock() - self.xmodule.has_score = True + self.xblock.verify_oauth_body_sign = Mock() + self.xblock.has_score = True request = Request(self.environ) request.body = self.get_request_body() - response = self.xmodule.grade_handler(request, '') + response = self.xblock.grade_handler(request, '') description_expected = 'Score for {sourcedId} is now {score}'.format( sourcedId=self.defaults['sourcedId'], score=self.defaults['grade'], @@ -293,11 +293,11 @@ class LTIBlockTest(TestCase): assert response.status_code == 200 self.assertDictEqual(expected_response, real_response) - assert self.xmodule.module_score == float(self.defaults['grade']) + assert self.xblock.module_score == float(self.defaults['grade']) def test_user_id(self): - expected_user_id = str(parse.quote(self.xmodule.runtime.anonymous_student_id)) - real_user_id = self.xmodule.get_user_id() + expected_user_id = str(parse.quote(self.xblock.runtime.anonymous_student_id)) + real_user_id = self.xblock.get_user_id() assert real_user_id == expected_user_id def test_outcome_service_url(self): @@ -308,24 +308,24 @@ class LTIBlockTest(TestCase): """Mock function for returning fully-qualified handler urls""" return mock_url_prefix + handler_name - self.xmodule.runtime.handler_url = Mock(side_effect=mock_handler_url) - real_outcome_service_url = self.xmodule.get_outcome_service_url(service_name=test_service_name) + self.xblock.runtime.handler_url = Mock(side_effect=mock_handler_url) + real_outcome_service_url = self.xblock.get_outcome_service_url(service_name=test_service_name) assert real_outcome_service_url == (mock_url_prefix + test_service_name) def test_resource_link_id(self): with patch('xmodule.lti_block.LTIBlock.location', new_callable=PropertyMock): - self.xmodule.location.html_id = lambda: 'i4x-2-3-lti-31de800015cf4afb973356dbe81496df' + self.xblock.location.html_id = lambda: 'i4x-2-3-lti-31de800015cf4afb973356dbe81496df' expected_resource_link_id = str(parse.quote(self.unquoted_resource_link_id)) - real_resource_link_id = self.xmodule.get_resource_link_id() + real_resource_link_id = self.xblock.get_resource_link_id() assert real_resource_link_id == expected_resource_link_id def test_lis_result_sourcedid(self): expected_sourced_id = ':'.join(parse.quote(i) for i in ( str(self.course_id), - self.xmodule.get_resource_link_id(), + self.xblock.get_resource_link_id(), self.user_id )) - real_lis_result_sourcedid = self.xmodule.get_lis_result_sourcedid() + real_lis_result_sourcedid = self.xblock.get_lis_result_sourcedid() assert real_lis_result_sourcedid == expected_sourced_id def test_client_key_secret(self): @@ -337,9 +337,9 @@ class LTIBlockTest(TestCase): modulestore = Mock() modulestore.get_course.return_value = mocked_course runtime = Mock(modulestore=modulestore) - self.xmodule.runtime = runtime - self.xmodule.lti_id = "lti_id" - key, secret = self.xmodule.get_client_key_secret() + self.xblock.runtime = runtime + self.xblock.lti_id = "lti_id" + key, secret = self.xblock.get_client_key_secret() expected = ('test_client', 'test_secret') assert expected == (key, secret) @@ -355,10 +355,10 @@ class LTIBlockTest(TestCase): modulestore = Mock() modulestore.get_course.return_value = mocked_course runtime = Mock(modulestore=modulestore) - self.xmodule.runtime = runtime + self.xblock.runtime = runtime # set another lti_id - self.xmodule.lti_id = "another_lti_id" - key_secret = self.xmodule.get_client_key_secret() + self.xblock.lti_id = "another_lti_id" + key_secret = self.xblock.get_client_key_secret() expected = ('', '') assert expected == key_secret @@ -373,10 +373,10 @@ class LTIBlockTest(TestCase): modulestore = Mock() modulestore.get_course.return_value = mocked_course runtime = Mock(modulestore=modulestore) - self.xmodule.runtime = runtime - self.xmodule.lti_id = 'lti_id' + self.xblock.runtime = runtime + self.xblock.lti_id = 'lti_id' with pytest.raises(LTIError): - self.xmodule.get_client_key_secret() + self.xblock.get_client_key_secret() @patch('xmodule.lti_block.signature.verify_hmac_sha1', Mock(return_value=True)) @patch( @@ -387,7 +387,7 @@ class LTIBlockTest(TestCase): """ Test if OAuth signing was successful. """ - self.xmodule.verify_oauth_body_sign(self.get_signed_grade_mock_request()) + self.xblock.verify_oauth_body_sign(self.get_signed_grade_mock_request()) @patch('xmodule.lti_block.LTIBlock.get_outcome_service_url', Mock(return_value='https://testurl/')) @patch('xmodule.lti_block.LTIBlock.get_client_key_secret', @@ -397,12 +397,12 @@ class LTIBlockTest(TestCase): Oauth signing verify fail. """ request = self.get_signed_grade_mock_request_with_correct_signature() - self.xmodule.verify_oauth_body_sign(request) + self.xblock.verify_oauth_body_sign(request) # we should verify against get_outcome_service_url not # request url proxy and load balancer along the way may # change url presented to the method request.url = 'http://testurl/' - self.xmodule.verify_oauth_body_sign(request) + self.xblock.verify_oauth_body_sign(request) def get_signed_grade_mock_request_with_correct_signature(self): """ @@ -445,7 +445,7 @@ class LTIBlockTest(TestCase): """ with pytest.raises(IndexError): mocked_request = self.get_signed_grade_mock_request(namespace_lti_v1p1=False) - self.xmodule.parse_grade_xml_body(mocked_request.body) + self.xblock.parse_grade_xml_body(mocked_request.body) def test_parse_grade_xml_body(self): """ @@ -454,7 +454,7 @@ class LTIBlockTest(TestCase): Tests that xml body was parsed successfully. """ mocked_request = self.get_signed_grade_mock_request() - message_identifier, sourced_id, grade, action = self.xmodule.parse_grade_xml_body(mocked_request.body) + message_identifier, sourced_id, grade, action = self.xblock.parse_grade_xml_body(mocked_request.body) assert self.defaults['messageIdentifier'] == message_identifier assert self.defaults['sourcedId'] == sourced_id assert self.defaults['grade'] == grade @@ -471,7 +471,7 @@ class LTIBlockTest(TestCase): """ with pytest.raises(LTIError): req = self.get_signed_grade_mock_request() - self.xmodule.verify_oauth_body_sign(req) + self.xblock.verify_oauth_body_sign(req) def get_signed_grade_mock_request(self, namespace_lti_v1p1=True): """ @@ -507,11 +507,11 @@ class LTIBlockTest(TestCase): """ Custom parameters are presented in right format. """ - self.xmodule.custom_parameters = ['test_custom_params=test_custom_param_value'] - self.xmodule.get_client_key_secret = Mock(return_value=('test_client_key', 'test_client_secret')) - self.xmodule.oauth_params = Mock() - self.xmodule.get_input_fields() - self.xmodule.oauth_params.assert_called_with( + self.xblock.custom_parameters = ['test_custom_params=test_custom_param_value'] + self.xblock.get_client_key_secret = Mock(return_value=('test_client_key', 'test_client_secret')) + self.xblock.oauth_params = Mock() + self.xblock.get_input_fields() + self.xblock.oauth_params.assert_called_with( {'custom_test_custom_params': 'test_custom_param_value'}, 'test_client_key', 'test_client_secret' ) @@ -521,24 +521,24 @@ class LTIBlockTest(TestCase): Custom parameters are presented in wrong format. """ bad_custom_params = ['test_custom_params: test_custom_param_value'] - self.xmodule.custom_parameters = bad_custom_params - self.xmodule.get_client_key_secret = Mock(return_value=('test_client_key', 'test_client_secret')) - self.xmodule.oauth_params = Mock() + self.xblock.custom_parameters = bad_custom_params + self.xblock.get_client_key_secret = Mock(return_value=('test_client_key', 'test_client_secret')) + self.xblock.oauth_params = Mock() with pytest.raises(LTIError): - self.xmodule.get_input_fields() + self.xblock.get_input_fields() def test_max_score(self): - self.xmodule.weight = 100.0 + self.xblock.weight = 100.0 - assert not self.xmodule.has_score - assert self.xmodule.max_score() is None + assert not self.xblock.has_score + assert self.xblock.max_score() is None - self.xmodule.has_score = True + self.xblock.has_score = True - assert self.xmodule.max_score() == 100.0 + assert self.xblock.max_score() == 100.0 def test_context_id(self): """ Tests that LTI parameter context_id is equal to course_id. """ - assert str(self.course_id) == self.xmodule.context_id + assert str(self.course_id) == self.xblock.context_id diff --git a/xmodule/tests/test_poll.py b/xmodule/tests/test_poll.py index f1a820d6c5..6fdf3f4592 100644 --- a/xmodule/tests/test_poll.py +++ b/xmodule/tests/test_poll.py @@ -30,13 +30,13 @@ class PollBlockTest(unittest.TestCase): usage_key = course_key.make_usage_key(PollBlock.category, 'test_loc') # ScopeIds has 4 fields: user_id, block_type, def_id, usage_id self.scope_ids = ScopeIds(1, PollBlock.category, usage_key, usage_key) - self.xmodule = PollBlock( + self.xblock = PollBlock( self.system, DictFieldData(self.raw_field_data), self.scope_ids ) def ajax_request(self, dispatch, data): """Call Xmodule.handle_ajax.""" - return json.loads(self.xmodule.handle_ajax(dispatch, data)) + return json.loads(self.xblock.handle_ajax(dispatch, data)) def test_bad_ajax_request(self): # Make sure that answer for incorrect request is error json. @@ -54,16 +54,16 @@ class PollBlockTest(unittest.TestCase): self.assertDictEqual(poll_answers, {'Yes': 1, 'Dont_know': 0, 'No': 1}) assert total == 2 self.assertDictEqual(callback, {'objectName': 'Conditional'}) - assert self.xmodule.poll_answer == 'No' + assert self.xblock.poll_answer == 'No' def test_poll_export_with_unescaped_characters_xml(self): """ Make sure that poll_block will export fine if its xml contains unescaped characters. """ - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) id_generator = Mock() - id_generator.target_course_id = self.xmodule.course_id + id_generator.target_course_id = self.xblock.course_id sample_poll_xml = '''

    How old are you?

    diff --git a/xmodule/tests/test_randomize_block.py b/xmodule/tests/test_randomize_block.py index bfbf78fbb9..8848c4dded 100644 --- a/xmodule/tests/test_randomize_block.py +++ b/xmodule/tests/test_randomize_block.py @@ -80,7 +80,7 @@ class RandomizeBlockTest(MixedSplitTestCase): # And compare. assert exported_olx == expected_olx - runtime = TestImportSystem(load_error_modules=True, course_id=randomize_block.location.course_key) + runtime = TestImportSystem(load_error_blocks=True, course_id=randomize_block.location.course_key) runtime.resources_fs = export_fs # Now import it. diff --git a/xmodule/tests/test_sequence.py b/xmodule/tests/test_sequence.py index 1fb744635c..4447bb2aed 100644 --- a/xmodule/tests/test_sequence.py +++ b/xmodule/tests/test_sequence.py @@ -1,5 +1,5 @@ """ -Tests for sequence module. +Tests for sequence block. """ # pylint: disable=no-member @@ -34,7 +34,7 @@ COURSE_END_DATE = TODAY + timedelta(days=21) @ddt.ddt class SequenceBlockTestCase(XModuleXmlImportTest): """ - Base class for tests of Sequence Module. + Base class for tests of Sequence Block. """ def setUp(self): @@ -88,7 +88,7 @@ class SequenceBlockTestCase(XModuleXmlImportTest): def _set_up_block(self, parent, index_in_parent): """ - Sets up the stub sequence module for testing. + Sets up the stub sequence block for testing. """ block = parent.get_children()[index_in_parent] diff --git a/xmodule/tests/test_split_test_block.py b/xmodule/tests/test_split_test_block.py index e5fb15c41a..5fae11c883 100644 --- a/xmodule/tests/test_split_test_block.py +++ b/xmodule/tests/test_split_test_block.py @@ -1,5 +1,5 @@ """ -Tests for the Split Testing Module +Tests for the Split Testing Block """ import json from unittest.mock import Mock, patch @@ -35,7 +35,7 @@ class SplitTestBlockFactory(xml.XmlImportFactory): class SplitTestUtilitiesTest(PartitionTestCase): """ - Tests for utility methods related to split_test module. + Tests for utility methods related to split_test block. """ def test_split_user_partitions(self): @@ -585,7 +585,7 @@ class SplitTestBlockExportImportTest(MixedSplitTestCase): # And compare. assert exported_olx == expected_olx - runtime = TestImportSystem(load_error_modules=True, course_id=split_test_block.location.course_key) + runtime = TestImportSystem(load_error_blocks=True, course_id=split_test_block.location.course_key) runtime.resources_fs = export_fs # Now import it. diff --git a/xmodule/tests/test_transcripts_utils.py b/xmodule/tests/test_transcripts_utils.py index 925a4cea20..0675dff2cf 100644 --- a/xmodule/tests/test_transcripts_utils.py +++ b/xmodule/tests/test_transcripts_utils.py @@ -104,7 +104,7 @@ class YoutubeVideoHTMLResponse: class TranscriptsUtilsTest(TestCase): """ - Tests utility fucntions for transcripts (in video_module) + Tests utility fucntions for transcripts (in video_block) """ @mock.patch('requests.get') diff --git a/xmodule/tests/test_vertical.py b/xmodule/tests/test_vertical.py index 22b06d3548..a7f993808f 100644 --- a/xmodule/tests/test_vertical.py +++ b/xmodule/tests/test_vertical.py @@ -1,5 +1,5 @@ """ -Tests for vertical module. +Tests for vertical block. """ # pylint: disable=protected-access @@ -89,7 +89,7 @@ class BaseVerticalBlockTest(XModuleXmlImportTest): def setUp(self): super().setUp() - # construct module: course/sequence/vertical - problems + # construct block: course/sequence/vertical - problems # \_ nested_vertical / problems course = xml.CourseFactory.build() sequence = xml.SequenceFactory.build(parent=course) diff --git a/xmodule/tests/test_video.py b/xmodule/tests/test_video.py index c21be47b56..b2bc1b41f0 100644 --- a/xmodule/tests/test_video.py +++ b/xmodule/tests/test_video.py @@ -1,5 +1,5 @@ # pylint: disable=protected-access -"""Test for Video Xmodule functional logic. +"""Test for Video XBlock functional logic. These test data read from xml, not from mongo. We have a ModuleStoreTestCase class defined in @@ -282,7 +282,7 @@ class VideoBlockImportTestCase(TestCase): }) def test_parse_xml(self): - module_system = DummySystem(load_error_modules=True) + module_system = DummySystem(load_error_blocks=True) xml_data = '''