Esempio n. 1
0
    def test_asset_import_nostatic(self):
        '''
        This test validates that an image asset is NOT imported when do_import_static=False
        '''
        content_store = contentstore()

        module_store = modulestore()
        import_from_xml(module_store,
                        self.user.id,
                        'common/test/data/', ['toy'],
                        static_content_store=content_store,
                        do_import_static=False,
                        verbose=True)

        course = module_store.get_course(
            SlashSeparatedCourseKey('edX', 'toy', '2012_Fall'))

        # make sure we have NO assets in our contentstore
        all_assets, count = content_store.get_all_content_for_course(course.id)
        self.assertEqual(len(all_assets), 0)
        self.assertEqual(count, 0)
Esempio n. 2
0
class XmlCoursesRenderTest(ModuleStoreTestCase):
    """Test methods related to rendering courses content for an XML course."""
    MODULESTORE = TEST_DATA_MIXED_TOY_MODULESTORE

    toy_course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')

    def test_get_course_info_section_render(self):
        course = get_course_by_id(self.toy_course_key)
        request = get_request_for_user(UserFactory.create())

        # Test render works okay. Note the href is different in XML courses.
        course_info = get_course_info_section(request, request.user, course, 'handouts')
        self.assertEqual(course_info, "<a href='/static/toy/handouts/sample_handout.txt'>Sample</a>")

        # Test when render raises an exception
        with mock.patch('courseware.courses.get_module') as mock_module_render:
            mock_module_render.return_value = mock.MagicMock(
                render=mock.Mock(side_effect=Exception('Render failed!'))
            )
            course_info = get_course_info_section(request, request.user, course, 'handouts')
            self.assertIn("this module is temporarily unavailable", course_info)
Esempio n. 3
0
    def test_post_course_update(self):
        """
        Test that a user can successfully post on course updates and handouts of a course
        """
        course_key = SlashSeparatedCourseKey('Org1', 'Course_1', 'Run_1')
        course_update_url = self.create_update_url(course_key=course_key)

        # create a course via the view handler
        self.client.ajax_post(course_update_url)

        block = u'updates'
        content = u"Sample update"
        payload = {'content': content, 'date': 'January 8, 2013'}
        resp = self.client.ajax_post(course_update_url, payload)

        # check that response status is 200 not 400
        self.assertEqual(resp.status_code, 200)

        payload = json.loads(resp.content)
        self.assertHTMLEqual(payload['content'], content)

        updates_location = self.course.id.make_usage_key(
            'course_info', 'updates')
        self.assertTrue(isinstance(updates_location, Location))
        self.assertEqual(updates_location.name, block)

        # check posting on handouts
        handouts_location = self.course.id.make_usage_key(
            'course_info', 'handouts')
        course_handouts_url = reverse_usage_url('xblock_handler',
                                                handouts_location)

        content = u"Sample handout"
        payload = {'data': content}
        resp = self.client.ajax_post(course_handouts_url, payload)
        # check that response status is 200 not 500
        self.assertEqual(resp.status_code, 200)

        payload = json.loads(resp.content)
        self.assertHTMLEqual(payload['data'], content)
Esempio n. 4
0
    def test_gitlog_courseteam_access(self):
        """
        Ensure course team users are allowed to access only their own course.
        """

        self._mkdir(getattr(settings, 'GIT_REPO_DIR'))

        self._setstaff_login()
        self._add_edx4edx()
        self.user.is_staff = False
        self.user.save()
        logged_in = self.client.login(username=self.user.username,
                                      password='******')
        response = self.client.get(reverse('gitlogs'))
        # Make sure our non privileged user doesn't have access to all logs
        self.assertEqual(response.status_code, 404)
        # Or specific logs
        response = self.client.get(reverse('gitlogs_detail', kwargs={
            'course_id': 'MITx/edx4edx/edx4edx'
        }))
        self.assertEqual(response.status_code, 404)

        # Add user as staff in course team
        def_ms = modulestore()
        course = def_ms.get_course(SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))
        CourseStaffRole(course.id).add_users(self.user)

        self.assertTrue(CourseStaffRole(course.id).has_user(self.user))
        logged_in = self.client.login(username=self.user.username,
                                      password='******')
        self.assertTrue(logged_in)

        response = self.client.get(
            reverse('gitlogs_detail', kwargs={
                'course_id': 'MITx/edx4edx/edx4edx'
            }))
        self.assertIn('======&gt; IMPORTING course',
                      response.content)

        self._rm_edx4edx()
Esempio n. 5
0
    def test_remap_namespace_native_xblock(self):

        # Set the XBlock's location
        self.xblock.location = Location("org", "import", "run", "category",
                                        "stubxblock")

        # Explicitly set the content and settings fields
        self.xblock.test_content_field = "Explicitly set"
        self.xblock.test_settings_field = "Explicitly set"
        self.xblock.save()

        # Move to different runtime w/ different course id
        target_location_namespace = SlashSeparatedCourseKey(
            "org", "course", "run")
        new_version = _import_module_and_update_references(
            self.xblock,
            modulestore(),
            999,
            self.xblock.location.course_key,
            target_location_namespace,
            do_import_static=False)

        # Check the XBlock's location
        self.assertEqual(new_version.location.course_key,
                         target_location_namespace)

        # Check the values of the fields.
        # The content and settings fields should be preserved
        self.assertEqual(new_version.test_content_field, 'Explicitly set')
        self.assertEqual(new_version.test_settings_field, 'Explicitly set')

        # Expect that these fields are marked explicitly set
        self.assertIn(
            'test_content_field',
            new_version.get_explicitly_set_fields_by_scope(
                scope=Scope.content))
        self.assertIn(
            'test_settings_field',
            new_version.get_explicitly_set_fields_by_scope(
                scope=Scope.settings))
Esempio n. 6
0
class CoursesRenderTest(ModuleStoreTestCase):
    """Test methods related to rendering courses content."""
    toy_course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')

    def test_get_course_info_section_render(self):
        course = get_course_by_id(self.toy_course_key)
        request = get_request_for_user(UserFactory.create())

        # Test render works okay
        course_info = get_course_info_section(request, course, 'handouts')
        self.assertEqual(
            course_info,
            "<a href='/static/toy/handouts/sample_handout.txt'>Sample</a>")

        # Test when render raises an exception
        with mock.patch('courseware.courses.get_module') as mock_module_render:
            mock_module_render.return_value = mock.MagicMock(render=mock.Mock(
                side_effect=Exception('Render failed!')))
            course_info = get_course_info_section(request, course, 'handouts')
            self.assertIn("this module is temporarily unavailable",
                          course_info)

    @mock.patch('courseware.courses.get_request_for_thread')
    def test_get_course_about_section_render(self, mock_get_request):
        course = get_course_by_id(self.toy_course_key)
        request = get_request_for_user(UserFactory.create())
        mock_get_request.return_value = request

        # Test render works okay
        course_about = get_course_about_section(course, 'short_description')
        self.assertEqual(course_about, "A course about toys.")

        # Test when render raises an exception
        with mock.patch('courseware.courses.get_module') as mock_module_render:
            mock_module_render.return_value = mock.MagicMock(render=mock.Mock(
                side_effect=Exception('Render failed!')))
            course_about = get_course_about_section(course,
                                                    'short_description')
            self.assertIn("this module is temporarily unavailable",
                          course_about)
Esempio n. 7
0
    def setUp(self):
        super(TestPeerGradingService, self).setUp()
        self.student = '*****@*****.**'
        self.instructor = '*****@*****.**'
        self.password = '******'
        self.create_account('u1', self.student, self.password)
        self.create_account('u2', self.instructor, self.password)
        self.activate_user(self.student)
        self.activate_user(self.instructor)

        self.course_id = SlashSeparatedCourseKey("edX", "toy", "2012_Fall")
        self.location_string = self.course_id.make_usage_key(
            'html', 'TestLocation').to_deprecated_string()
        self.toy = modulestore().get_course(self.course_id)
        location = "i4x://edX/toy/peergrading/init"
        field_data = DictFieldData({
            'data': "<peergrading/>",
            'location': location,
            'category': 'peergrading'
        })
        self.mock_service = peer_grading_service.MockPeerGradingService()
        self.system = LmsModuleSystem(
            static_url=settings.STATIC_URL,
            track_function=None,
            get_module=None,
            render_template=render_to_string,
            replace_urls=None,
            s3_interface=test_util_open_ended.S3_INTERFACE,
            open_ended_grading_interface=test_util_open_ended.
            OPEN_ENDED_GRADING_INTERFACE,
            mixins=settings.XBLOCK_MIXINS,
            error_descriptor_class=ErrorDescriptor,
            descriptor_runtime=None,
        )
        self.descriptor = peer_grading_module.PeerGradingDescriptor(
            self.system, field_data, ScopeIds(None, None, None, None))
        self.descriptor.xmodule_runtime = self.system
        self.peer_module = self.descriptor
        self.peer_module.peer_gs = self.mock_service
        self.logout()
    def test_translate_location_dwim(self):
        """
        Test the location translation mechanisms which try to do-what-i-mean by creating new
        entries for never seen queries.
        """
        org = 'foo_org'
        course = 'bar_course'
        run = 'baz_run'
        problem_name = 'abc123abc123abc123abc123abc123f9'
        location = Location(org, course, run, 'problem', problem_name)
        new_offering = '{}.{}'.format(course, run)
        self.translate_n_check(location, org, new_offering, 'problemabc', 'published', True)

        # create an entry w/o a guid name
        other_location = Location(org, course, run, 'chapter', 'intro')
        self.translate_n_check(other_location, org, new_offering, 'intro', 'published', True)

        # add a distractor course
        delta_new_org = '{}.geek_dept'.format(org)
        run = 'delta_run'
        delta_new_offering = '{}.{}'.format(course, run)
        delta_course_locn = SlashSeparatedCourseKey(org, course, run)
        loc_mapper().create_map_entry(
            delta_course_locn,
            delta_new_org, delta_new_offering,
            block_map={problem_name: {'problem': 'problem3'}}
        )
        self.translate_n_check(location, org, new_offering, 'problemabc', 'published', True)

        # add a new one to both courses (ensure name doesn't have same beginning)
        new_prob_name = uuid.uuid4().hex
        while new_prob_name.startswith('abc'):
            new_prob_name = uuid.uuid4().hex
        new_prob_locn = location.replace(name=new_prob_name)
        new_usage_id = 'problem{}'.format(new_prob_name[:3])
        self.translate_n_check(new_prob_locn, org, new_offering, new_usage_id, 'published', True)
        new_prob_locn = new_prob_locn.replace(run=run)
        self.translate_n_check(
            new_prob_locn, delta_new_org, delta_new_offering, new_usage_id, 'published', True
        )
Esempio n. 9
0
 def get_courses(self):
     '''
     Returns a list of course descriptors.
     '''
     base_list = sum(
         [
             self._load_items(
                 SlashSeparatedCourseKey(course['_id']['org'], course['_id']['course'], course['_id']['name']),
                 [course]
             )
             for course
             # I tried to add '$and': [{'_id.org': {'$ne': 'edx'}}, {'_id.course': {'$ne': 'templates'}}]
             # but it didn't do the right thing (it filtered all edx and all templates out)
             in self.collection.find({'_id.category': 'course'})
             if not (  # TODO kill this
                 course['_id']['org'] == 'edx' and
                 course['_id']['course'] == 'templates'
             )
         ],
         []
     )
     return [course for course in base_list if not isinstance(course, ErrorDescriptor)]
Esempio n. 10
0
    def setUp(self):
        clear_existing_modulestores()
        courses = modulestore().get_courses()

        self.course_id = SlashSeparatedCourseKey("edX", "toy", "2012_Fall")
        self.toy = modulestore().get_course(self.course_id)

        # Create two accounts
        self.student = '*****@*****.**'
        self.instructor = '*****@*****.**'
        self.password = '******'
        self.create_account('u1', self.student, self.password)
        self.create_account('u2', self.instructor, self.password)
        self.activate_user(self.student)
        self.activate_user(self.instructor)

        CourseStaffRole(self.toy.id).add_users(
            User.objects.get(email=self.instructor))

        self.logout()
        self.login(self.instructor, self.password)
        self.enroll(self.toy)
Esempio n. 11
0
    def test_get_cohort_id(self):
        """
        Make sure that cohorts.get_cohort_id() correctly returns the cohort id, or raises a ValueError when given an
        invalid course key.
        """
        course = modulestore().get_course(self.toy_course_key)
        self.assertFalse(course.is_cohorted)

        user = User.objects.create(username="******", email="*****@*****.**")
        self.assertIsNone(cohorts.get_cohort_id(user, course.id))

        config_course_cohorts(course, [], cohorted=True)
        cohort = CourseUserGroup.objects.create(
            name="TestCohort",
            course_id=course.id,
            group_type=CourseUserGroup.COHORT)
        cohort.users.add(user)
        self.assertEqual(cohorts.get_cohort_id(user, course.id), cohort.id)

        self.assertRaises(
            ValueError, lambda: cohorts.get_cohort_id(
                user, SlashSeparatedCourseKey("course", "does_not", "exist")))
Esempio n. 12
0
    def _rm_edx4edx(self):
        """Deletes the sample course from the XML store"""
        def_ms = modulestore()
        course_path = '{0}/edx4edx_lite'.format(
            os.path.abspath(settings.DATA_DIR))
        try:
            # using XML store
            course = def_ms.courses.get(course_path, None)
        except AttributeError:
            # Using mongo store
            course = def_ms.get_course(
                SlashSeparatedCourseKey('MITx', 'edx4edx', 'edx4edx'))

        # Delete git loaded course
        response = self.client.post(
            reverse('sysadmin_courses'), {
                'course_id': course.id.to_deprecated_string(),
                'action': 'del_course',
            })
        self.addCleanup(self._rm_glob, '{0}_deleted_*'.format(course_path))

        return response
Esempio n. 13
0
    def test_url_name_mangling(self):
        """
        Make sure that url_names are only mangled once.
        """

        modulestore = XMLModuleStore(DATA_DIR, source_dirs=['toy'])

        toy_id = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')

        course = modulestore.get_course(toy_id)
        chapters = course.get_children()
        ch1 = chapters[0]
        sections = ch1.get_children()

        self.assertEqual(len(sections), 4)

        for i in (2, 3):
            video = sections[i]
            # Name should be 'video_{hash}'
            print("video {0} url_name: {1}".format(i, video.url_name))

            self.assertEqual(len(video.url_name), len('video_') + 12)
Esempio n. 14
0
    def setUp(self):
        self.course_key = SlashSeparatedCourseKey('edX', 'toy', '2012_Fall')
        self.location = self.course_key.make_usage_key('chapter', 'Overview')
        self.toy_course = modulestore().get_course(self.course_key)
        self.mock_user = UserFactory()
        self.mock_user.id = 1
        self.request_factory = RequestFactory()

        # Construct a mock module for the modulestore to return
        self.mock_module = MagicMock()
        self.mock_module.id = 1
        self.dispatch = 'score_update'

        # Construct a 'standard' xqueue_callback url
        self.callback_url = reverse(
            'xqueue_callback', kwargs={
                'course_id': self.course_key.to_deprecated_string(),
                'userid': str(self.mock_user.id),
                'mod_id': self.mock_module.id,
                'dispatch': self.dispatch
            }
        )
Esempio n. 15
0
 def test_creation_with_optional_attributes(self):
     course_id = SlashSeparatedCourseKey('abc', '123', 'doremi')
     sender = UserFactory.create()
     to_option = SEND_TO_STAFF
     subject = "dummy subject"
     html_message = "<html>dummy message</html>"
     template_name = "branded_template"
     from_addr = "*****@*****.**"
     email = CourseEmail.create(course_id,
                                sender,
                                to_option,
                                subject,
                                html_message,
                                template_name=template_name,
                                from_addr=from_addr)
     self.assertEquals(email.course_id, course_id)
     self.assertEquals(email.to_option, SEND_TO_STAFF)
     self.assertEquals(email.subject, subject)
     self.assertEquals(email.html_message, html_message)
     self.assertEquals(email.sender, sender)
     self.assertEquals(email.template_name, template_name)
     self.assertEquals(email.from_addr, from_addr)
Esempio n. 16
0
    def load_test_import_course(self):
        '''
        Load the standard course used to test imports
        (for do_import_static=False behavior).
        '''
        content_store = contentstore()
        module_store = modulestore()
        import_from_xml(
            module_store,
            self.user.id,
            'common/test/data/',
            ['test_import_course'],
            static_content_store=content_store,
            do_import_static=False,
            verbose=True,
        )
        course_id = SlashSeparatedCourseKey('edX', 'test_import_course',
                                            '2012_Fall')
        course = module_store.get_course(course_id)
        self.assertIsNotNone(course)

        return module_store, content_store, course
Esempio n. 17
0
    def test_errored_course_global_staff(self):
        """
        Test the course list for global staff when get_course returns an ErrorDescriptor
        """
        GlobalStaff().add_users(self.user)

        course_key = SlashSeparatedCourseKey('Org1', 'Course1', 'Run1')
        self._create_course_with_access_groups(course_key, self.user)

        with patch('xmodule.modulestore.mongo.base.MongoKeyValueStore',
                   Mock(side_effect=Exception)):
            self.assertIsInstance(modulestore().get_course(course_key),
                                  ErrorDescriptor)

            # get courses through iterating all courses
            courses_list = _accessible_courses_list(self.request)
            self.assertEqual(courses_list, [])

            # get courses by reversing group name formats
            courses_list_by_groups = _accessible_courses_list_from_groups(
                self.request)
            self.assertEqual(courses_list_by_groups, [])
Esempio n. 18
0
 def setUp(self):
     self.user = UserFactory.create(username="******", password="******")
     self.client.login(username="******", password="******")
     self.course_id = 'Robot/999/Test_Course'
     self.course = CourseFactory.create(org='Robot', number='999', display_name='Test Course')
     verified_mode = CourseMode(
         course_id=SlashSeparatedCourseKey("Robot", "999", 'Test_Course'),
         mode_slug="verified",
         mode_display_name="Verified Certificate",
         min_price=50
     )
     verified_mode.save()
     course_mode_post_data = {
         'certificate_mode': 'Select Certificate',
         'contribution': 50,
         'contribution-other-amt': '',
         'explain': ''
     }
     self.client.post(
         reverse("course_modes_choose", kwargs={'course_id': self.course_id}),
         course_mode_post_data
     )
Esempio n. 19
0
    def test_export_course_image(self, _from_json):
        """
        Test to make sure that we have a course image in the contentstore,
        then export it to ensure it gets copied to both file locations.
        """
        course_key = SlashSeparatedCourseKey('edX', 'simple', '2012_Fall')
        location = course_key.make_asset_key('asset',
                                             'images_course_image.jpg')

        # This will raise if the course image is missing
        self.content_store.find(location)

        root_dir = path(mkdtemp())
        self.addCleanup(shutil.rmtree, root_dir)
        export_course_to_xml(self.draft_store, self.content_store, course_key,
                             root_dir, 'test_export')
        self.assertTrue(
            path(root_dir /
                 'test_export/static/images/course_image.jpg').isfile())
        self.assertTrue(
            path(root_dir /
                 'test_export/static/images_course_image.jpg').isfile())
Esempio n. 20
0
def get_test_system(course_id=SlashSeparatedCourseKey('org', 'course', 'run')):
    """
    Construct a test ModuleSystem instance.

    By default, the render_template() method simply returns the repr of the
    context it is passed.  You can override this behavior by monkey patching::

        system = get_test_system()
        system.render_template = my_render_func

    where `my_render_func` is a function of the form my_render_func(template, context).

    """
    return TestModuleSystem(
        static_url='/static',
        track_function=Mock(),
        get_module=Mock(),
        render_template=mock_render_template,
        replace_urls=str,
        user=Mock(is_staff=False),
        filestore=Mock(),
        debug=True,
        hostname="edx.org",
        xqueue={
            'interface': None,
            'callback_url': '/',
            'default_queuename': 'testqueue',
            'waittime': 10,
            'construct_callback': Mock(side_effect="/")
        },
        node_path=os.environ.get("NODE_PATH", "/usr/local/lib/node_modules"),
        anonymous_student_id='student',
        open_ended_grading_interface=open_ended_grading_interface,
        course_id=course_id,
        error_descriptor_class=ErrorDescriptor,
        get_user_role=Mock(is_staff=False),
        descriptor_runtime=get_test_descriptor_system(),
        user_location=Mock(),
    )
Esempio n. 21
0
def make_an_xblock(**kwargs):
    """
    Helper method that creates a Free-text Response XBlock
    """
    course_id = SlashSeparatedCourseKey('foo', 'bar', 'baz')
    services = {
        'i18n':
        Mock(ugettext=lambda string: string),
        'user':
        Mock(get_current_user=lambda: Mock(
            emails=['*****@*****.**'],
            opt_attrs={},
        ), )
    }
    runtime = Mock(
        course_id=course_id,
        service=lambda _, service: services.get(service),
    )
    scope_ids = Mock()
    field_data = DictFieldData(kwargs)
    xblock = GradeMeButton(runtime, field_data, scope_ids)
    xblock.xmodule_runtime = runtime
    return xblock
Esempio n. 22
0
class CohortFactory(DjangoModelFactory):
    """
    Factory for constructing mock cohorts.
    """
    class Meta(object):
        model = CourseUserGroup

    name = Sequence("cohort{}".format)
    course_id = SlashSeparatedCourseKey("dummy", "dummy", "dummy")
    group_type = CourseUserGroup.COHORT

    @post_generation
    def users(self, create, extracted, **kwargs):  # pylint: disable=unused-argument
        """
        Returns the users associated with the cohort.
        """
        if extracted:
            self.users.add(*extracted)
            for user in self.users.all():
                CohortMembership.objects.create(
                    user=user,
                    course_user_group=self,
                )
Esempio n. 23
0
 def test_get_modulestore_type(self, default_ms):
     """
     Make sure we get back the store type we expect for given mappings
     """
     self.initdb(default_ms)
     self.assertEqual(
         self.store.get_modulestore_type(
             self._course_key_from_string(self.XML_COURSEID1)),
         XML_MODULESTORE_TYPE)
     self.assertEqual(
         self.store.get_modulestore_type(
             self._course_key_from_string(self.XML_COURSEID2)),
         XML_MODULESTORE_TYPE)
     mongo_ms_type = MONGO_MODULESTORE_TYPE if default_ms == 'direct' else SPLIT_MONGO_MODULESTORE_TYPE
     self.assertEqual(
         self.store.get_modulestore_type(
             self._course_key_from_string(self.MONGO_COURSEID)),
         mongo_ms_type)
     # try an unknown mapping, it should be the 'default' store
     self.assertEqual(
         self.store.get_modulestore_type(
             SlashSeparatedCourseKey('foo', 'bar', '2012_Fall')),
         mongo_ms_type)
Esempio n. 24
0
    def test_creation_auth_on(self):
        BulkEmailFlag.objects.create(enabled=True,
                                     require_course_email_auth=True)
        course_id = SlashSeparatedCourseKey('abc', '123', 'doremi')
        # Test that course is not authorized by default
        self.assertFalse(BulkEmailFlag.feature_enabled(course_id))

        # Authorize
        cauth = CourseAuthorization(course_id=course_id, email_enabled=True)
        cauth.save()
        # Now, course should be authorized
        self.assertTrue(BulkEmailFlag.feature_enabled(course_id))
        self.assertEquals(cauth.__unicode__(),
                          "Course 'abc/123/doremi': Instructor Email Enabled")

        # Unauthorize by explicitly setting email_enabled to False
        cauth.email_enabled = False
        cauth.save()
        # Test that course is now unauthorized
        self.assertFalse(BulkEmailFlag.feature_enabled(course_id))
        self.assertEquals(
            cauth.__unicode__(),
            "Course 'abc/123/doremi': Instructor Email Not Enabled")
Esempio n. 25
0
    def test_get_cohort_by_name(self):
        """
        Make sure cohorts.get_cohort_by_name() properly finds a cohort by name for a given course.  Also verify that it
        raises an error when the cohort is not found.
        """
        course = modulestore().get_course(self.toy_course_key)

        self.assertRaises(
            CourseUserGroup.DoesNotExist, lambda: cohorts.get_cohort_by_name(
                course.id, "CohortDoesNotExist"))

        cohort = CourseUserGroup.objects.create(
            name="MyCohort",
            course_id=course.id,
            group_type=CourseUserGroup.COHORT)

        self.assertEqual(cohorts.get_cohort_by_name(course.id, "MyCohort"),
                         cohort)

        self.assertRaises(
            CourseUserGroup.DoesNotExist, lambda: cohorts.get_cohort_by_name(
                SlashSeparatedCourseKey("course", "does_not", "exist"), cohort)
        )
Esempio n. 26
0
    def test_unicode_chars_in_xml_content(self):
        # edX/full/6.002_Spring_2012 has non-ASCII chars, and during
        # uniquification of names, would raise a UnicodeError. It no longer does.

        # Ensure that there really is a non-ASCII character in the course.
        with open(
                os.path.join(
                    DATA_DIR,
                    "toy/sequential/vertical_sequential.xml")) as xmlf:
            xml = xmlf.read()
            with self.assertRaises(UnicodeDecodeError):
                xml.decode('ascii')

        # Load the course, but don't make error modules.  This will succeed,
        # but will record the errors.
        modulestore = XMLModuleStore(DATA_DIR,
                                     course_dirs=['toy'],
                                     load_error_modules=False)

        # Look up the errors during load. There should be none.
        errors = modulestore.get_course_errors(
            SlashSeparatedCourseKey("edX", "toy", "2012_Fall"))
        assert errors == []
Esempio n. 27
0
    def test_add_cohort(self, mock_tracker):
        """
        Make sure cohorts.add_cohort() properly adds a cohort to a course and handles
        errors.
        """
        assignment_type = CourseCohort.RANDOM
        course = modulestore().get_course(self.toy_course_key)
        added_cohort = cohorts.add_cohort(course.id, "My Cohort", assignment_type)
        mock_tracker.emit.assert_any_call(
            "edx.cohort.creation_requested",
            {"cohort_name": added_cohort.name, "cohort_id": added_cohort.id}
        )

        self.assertEqual(added_cohort.name, "My Cohort")
        self.assertRaises(
            ValueError,
            lambda: cohorts.add_cohort(course.id, "My Cohort", assignment_type)
        )
        does_not_exist_course_key = SlashSeparatedCourseKey("course", "does_not", "exist")
        self.assertRaises(
            ValueError,
            lambda: cohorts.add_cohort(does_not_exist_course_key, "My Cohort", assignment_type)
        )
Esempio n. 28
0
class StaticTabDateTestCaseXML(LoginEnrollmentTestCase, ModuleStoreTestCase):
    """
    Tests for the static tab dates of an XML course
    """

    MODULESTORE = TEST_DATA_MIXED_CLOSED_MODULESTORE

    # The following XML test course (which lives at common/test/data/2014)
    # is closed; we're testing that tabs still appear when
    # the course is already closed
    xml_course_key = SlashSeparatedCourseKey('edX', 'detached_pages', '2014')

    # this text appears in the test course's tab
    # common/test/data/2014/tabs/8e4cce2b4aaf4ba28b1220804619e41f.html
    xml_data = "static 463139"
    xml_url = "8e4cce2b4aaf4ba28b1220804619e41f"

    @patch.dict('django.conf.settings.FEATURES',
                {'DISABLE_START_DATES': False})
    def test_logged_in_xml(self):
        self.setup_user()
        url = reverse(
            'static_tab',
            args=[self.xml_course_key.to_deprecated_string(), self.xml_url])
        resp = self.client.get(url)
        self.assertEqual(resp.status_code, 200)
        self.assertIn(self.xml_data, resp.content)

    @patch.dict('django.conf.settings.FEATURES',
                {'DISABLE_START_DATES': False})
    def test_anonymous_user_xml(self):
        url = reverse(
            'static_tab',
            args=[self.xml_course_key.to_deprecated_string(), self.xml_url])
        resp = self.client.get(url)
        self.assertEqual(resp.status_code, 200)
        self.assertIn(self.xml_data, resp.content)
Esempio n. 29
0
    def test_get_cohorted_commentables(self):
        """
        Make sure cohorts.get_cohorted_commentables() correctly returns a list of strings representing cohorted
        commentables.  Also verify that we can't get the cohorted commentables from a course which does not exist.
        """
        course = modulestore().get_course(self.toy_course_key)

        self.assertEqual(cohorts.get_cohorted_commentables(course.id), set())

        config_course_cohorts(course, is_cohorted=True)
        self.assertEqual(cohorts.get_cohorted_commentables(course.id), set())

        config_course_cohorts(
            course,
            is_cohorted=True,
            discussion_topics=["General", "Feedback"],
            cohorted_discussions=["Feedback"]
        )
        self.assertItemsEqual(
            cohorts.get_cohorted_commentables(course.id),
            set([topic_name_to_id(course, "Feedback")])
        )

        config_course_cohorts(
            course,
            is_cohorted=True,
            discussion_topics=["General", "Feedback"],
            cohorted_discussions=["General", "Feedback"]
        )
        self.assertItemsEqual(
            cohorts.get_cohorted_commentables(course.id),
            set([topic_name_to_id(course, "General"), topic_name_to_id(course, "Feedback")])
        )
        self.assertRaises(
            Http404,
            lambda: cohorts.get_cohorted_commentables(SlashSeparatedCourseKey("course", "does_not", "exist"))
        )
Esempio n. 30
0
    def setUp(self):
        """
        Create a staff user and log them in (creating the client).

        Create a pool of users w/o granting them any permissions
        """
        super(TestCourseAccess, self).setUp()
        uname = 'testuser'
        email = '*****@*****.**'
        password = '******'

        # Create the use so we can log them in.
        self.user = User.objects.create_user(uname, email, password)

        # Note that we do not actually need to do anything
        # for registration if we directly mark them active.
        self.user.is_active = True
        # Staff has access to view all courses
        self.user.is_staff = True
        self.user.save()

        self.client = AjaxEnabledTestClient()
        self.client.login(username=uname, password=password)

        # create a course via the view handler which has a different strategy for permissions than the factory
        self.course_key = SlashSeparatedCourseKey('myu', 'mydept.mycourse',
                                                  'myrun')
        course_url = reverse_url('course_handler')
        self.client.ajax_post(
            course_url, {
                'org': self.course_key.org,
                'number': self.course_key.course,
                'display_name': 'My favorite course',
                'run': self.course_key.run,
            })

        self.users = self._create_users()