Example #1
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestFieldOverrides, self).setUp()

        self.ccx = ccx = CustomCourseForEdX(
            course_id=self.course.id,
            display_name='Test CCX',
            coach=AdminFactory.create())
        ccx.save()

        patch = mock.patch('ccx.overrides.get_current_ccx')
        self.get_ccx = get_ccx = patch.start()
        get_ccx.return_value = ccx
        self.addCleanup(patch.stop)

        self.addCleanup(RequestCache.clear_request_cache)

        inject_field_overrides(iter_blocks(ccx.course), self.course, AdminFactory.create())

        self.ccx_key = CCXLocator.from_course_locator(self.course.id, ccx.id)
        self.ccx_course = get_course_by_id(self.ccx_key, depth=None)

        def cleanup_provider_classes():
            """
            After everything is done, clean up by un-doing the change to the
            OverrideFieldData object that is done during the wrap method.
            """
            OverrideFieldData.provider_classes = None
        self.addCleanup(cleanup_provider_classes)
Example #2
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestFieldOverrides, self).setUp()
        self.course = course = CourseFactory.create()
        self.course.enable_ccx = True

        # Create a course outline
        self.mooc_start = start = datetime.datetime(
            2010, 5, 12, 2, 42, tzinfo=pytz.UTC)
        self.mooc_due = due = datetime.datetime(
            2010, 7, 7, 0, 0, tzinfo=pytz.UTC)
        chapters = [ItemFactory.create(start=start, parent=course)
                    for _ in xrange(2)]
        sequentials = flatten([
            [ItemFactory.create(parent=chapter) for _ in xrange(2)]
            for chapter in chapters])
        verticals = flatten([
            [ItemFactory.create(due=due, parent=sequential) for _ in xrange(2)]
            for sequential in sequentials])
        blocks = flatten([  # pylint: disable=unused-variable
            [ItemFactory.create(parent=vertical) for _ in xrange(2)]
            for vertical in verticals])

        self.ccx = ccx = CustomCourseForEdX(
            course_id=course.id,
            display_name='Test CCX',
            coach=AdminFactory.create())
        ccx.save()

        patch = mock.patch('ccx.overrides.get_current_ccx')
        self.get_ccx = get_ccx = patch.start()
        get_ccx.return_value = ccx
        self.addCleanup(patch.stop)

        self.addCleanup(RequestCache.clear_request_cache)

        # Apparently the test harness doesn't use LmsFieldStorage, and I'm not
        # sure if there's a way to poke the test harness to do so.  So, we'll
        # just inject the override field storage in this brute force manner.
        OverrideFieldData.provider_classes = None
        for block in iter_blocks(ccx.course):
            block._field_data = OverrideFieldData.wrap(   # pylint: disable=protected-access
                AdminFactory.create(), course, block._field_data)   # pylint: disable=protected-access

        def cleanup_provider_classes():
            """
            After everything is done, clean up by un-doing the change to the
            OverrideFieldData object that is done during the wrap method.
            """
            OverrideFieldData.provider_classes = None
        self.addCleanup(cleanup_provider_classes)
Example #3
0
    def setUp(self):
        patcher = patch('student.models.tracker')
        self.mock_tracker = patcher.start()
        self.user = UserFactory.create()
        self.user.set_password('password')
        self.user.save()
        self.instructor = AdminFactory.create()
        self.cost = 40
        self.coupon_code = 'abcde'
        self.reg_code = 'qwerty'
        self.percentage_discount = 10
        self.course = CourseFactory.create(org='MITx', number='999', display_name='Robot Super Course')
        self.course_key = self.course.id
        self.course_mode = CourseMode(course_id=self.course_key,
                                      mode_slug="honor",
                                      mode_display_name="honor cert",
                                      min_price=self.cost)
        self.course_mode.save()

        #Saving another testing course mode
        self.testing_cost = 20
        self.testing_course = CourseFactory.create(org='edX', number='888', display_name='Testing Super Course')
        self.testing_course_mode = CourseMode(course_id=self.testing_course.id,
                                              mode_slug="honor",
                                              mode_display_name="testing honor cert",
                                              min_price=self.testing_cost)
        self.testing_course_mode.save()

        verified_course = CourseFactory.create(org='org', number='test', display_name='Test Course')
        self.verified_course_key = verified_course.id
        self.cart = Order.get_cart_for_user(self.user)
        self.addCleanup(patcher.stop)
Example #4
0
    def setUp(self):
        patcher = patch("student.models.tracker")
        self.mock_tracker = patcher.start()
        self.user = UserFactory.create()
        self.user.set_password("password")
        self.user.save()
        self.instructor = AdminFactory.create()
        self.cost = 40
        self.coupon_code = "abcde"
        self.reg_code = "qwerty"
        self.percentage_discount = 10
        self.course = CourseFactory.create(org="MITx", number="999", display_name="Robot Super Course")
        self.course_key = self.course.id
        self.course_mode = CourseMode(
            course_id=self.course_key, mode_slug="honor", mode_display_name="honor cert", min_price=self.cost
        )
        self.course_mode.save()

        # Saving another testing course mode
        self.testing_cost = 20
        self.testing_course = CourseFactory.create(org="edX", number="888", display_name="Testing Super Course")
        self.testing_course_mode = CourseMode(
            course_id=self.testing_course.id,
            mode_slug="honor",
            mode_display_name="testing honor cert",
            min_price=self.testing_cost,
        )
        self.testing_course_mode.save()

        verified_course = CourseFactory.create(org="org", number="test", display_name="Test Course")
        self.verified_course_key = verified_course.id
        self.cart = Order.get_cart_for_user(self.user)
        self.addCleanup(patcher.stop)
Example #5
0
    def setUp(self):
        super(TeamAPITestCase, self).setUp()
        self.topics_count = 4
        self.users = {
            "student_unenrolled": UserFactory.create(password=self.test_password),
            "student_enrolled": UserFactory.create(password=self.test_password),
            "student_enrolled_not_on_team": UserFactory.create(password=self.test_password),
            # This student is enrolled in both test courses and is a member of a team in each course, but is not on the
            # same team as student_enrolled.
            "student_enrolled_both_courses_other_team": UserFactory.create(password=self.test_password),
            "staff": AdminFactory.create(password=self.test_password),
            "course_staff": StaffFactory.create(course_key=self.test_course_1.id, password=self.test_password),
        }
        # 'solar team' is intentionally lower case to test case insensitivity in name ordering
        self.test_team_1 = CourseTeamFactory.create(
            name=u"sólar team", course_id=self.test_course_1.id, topic_id="topic_0"
        )
        self.test_team_2 = CourseTeamFactory.create(name="Wind Team", course_id=self.test_course_1.id)
        self.test_team_3 = CourseTeamFactory.create(name="Nuclear Team", course_id=self.test_course_1.id)
        self.test_team_4 = CourseTeamFactory.create(name="Coal Team", course_id=self.test_course_1.id, is_active=False)
        self.test_team_5 = CourseTeamFactory.create(name="Another Team", course_id=self.test_course_2.id)

        for user, course in [
            ("student_enrolled", self.test_course_1),
            ("student_enrolled_not_on_team", self.test_course_1),
            ("student_enrolled_both_courses_other_team", self.test_course_1),
            ("student_enrolled_both_courses_other_team", self.test_course_2),
        ]:
            CourseEnrollment.enroll(self.users[user], course.id, check_access=True)

        self.test_team_1.add_user(self.users["student_enrolled"])
        self.test_team_3.add_user(self.users["student_enrolled_both_courses_other_team"])
        self.test_team_5.add_user(self.users["student_enrolled_both_courses_other_team"])
    def setUp(self):
        super(TestGetProblemGradeDistribution, self).setUp()

        self.request_factory = RequestFactory()
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password='******')
        self.attempts = 3
        self.users = [
            UserFactory.create(username="******" + str(__))
            for __ in xrange(USER_COUNT)
        ]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i, item in enumerate(self.items):
            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    grade=1 if i < j else 0,
                    max_grade=1 if i < j else 0.5,
                    student=user,
                    course_id=self.course.id,
                    module_state_key=item.location,
                    state=json.dumps({'attempts': self.attempts}),
                )
            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    course_id=self.course.id,
                    module_type='sequential',
                    module_state_key=item.location,
                )
 def setUp(self):
     """Set up a course, coach, ccx and user"""
     super(TestGetCCXFromCCXLocator, self).setUp()
     self.course = CourseFactory.create()
     coach = self.coach = AdminFactory.create()
     role = CourseCcxCoachRole(self.course.id)
     role.add_users(coach)
    def setUp(self):
        """
        Set up tests
        """
        super(TestInstructorDashboard, self).setUp()
        self.course = CourseFactory.create(
            grading_policy={"GRADE_CUTOFFS": {"A": 0.75, "B": 0.63, "C": 0.57, "D": 0.5}},
            display_name='<script>alert("XSS")</script>'
        )

        self.course_mode = CourseMode(
            course_id=self.course.id,
            mode_slug=CourseMode.DEFAULT_MODE_SLUG,
            mode_display_name=CourseMode.DEFAULT_MODE.name,
            min_price=40
        )
        self.course_info = CourseFactory.create(
            org="ACME",
            number="001",
            run="2017",
            name="How to defeat the Road Runner"
        )
        self.course_mode.save()
        # Create instructor account
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password="******")

        # URL for instructor dash
        self.url = reverse('instructor_dashboard', kwargs={'course_id': text_type(self.course.id)})
Example #9
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestCCXGrades, self).setUp()

        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create CCX
        role = CourseCcxCoachRole(self._course.id)
        role.add_users(coach)
        ccx = CcxFactory(course_id=self._course.id, coach=self.coach)

        # override course grading policy and make last section invisible to students
        override_field_for_ccx(
            ccx,
            self._course,
            "grading_policy",
            {
                "GRADER": [{"drop_count": 0, "min_count": 2, "short_label": "HW", "type": "Homework", "weight": 1}],
                "GRADE_CUTOFFS": {"Pass": 0.75},
            },
        )
        override_field_for_ccx(ccx, self.sections[-1], "visible_to_staff_only", True)

        # create a ccx locator and retrieve the course structure using that key
        # which emulates how a student would get access.
        self.ccx_key = CCXLocator.from_course_locator(self._course.id, ccx.id)
        self.course = get_course_by_id(self.ccx_key, depth=None)
        setup_students_and_grades(self)
        self.client.login(username=coach.username, password="******")
        self.addCleanup(RequestCache.clear_request_cache)
 def setUpTestData(cls):
     """
     Set up models for the whole TestCase.
     """
     cls.user = UserFactory.create()
     # Create instructor account
     cls.coach = AdminFactory.create()
Example #11
0
 def test_patch_detail(self):
     """
     Test for successful patch
     """
     outbox = self.get_outbox()
     # create a new coach
     new_coach = AdminFactory.create()
     data = {
         'max_students_allowed': 111,
         'display_name': 'CCX Title',
         'coach_email': new_coach.email
     }
     resp = self.client.patch(self.detail_url, data, format='json', HTTP_AUTHORIZATION=self.auth)
     self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
     ccx_from_db = CustomCourseForEdX.objects.get(id=self.ccx.id)
     self.assertEqual(ccx_from_db.max_student_enrollments_allowed, data['max_students_allowed'])
     self.assertEqual(ccx_from_db.display_name, data['display_name'])
     self.assertEqual(ccx_from_db.coach.email, data['coach_email'])
     # check that the coach user has coach role on the master course
     coach_role_on_master_course = CourseCcxCoachRole(self.master_course_key)
     self.assertTrue(coach_role_on_master_course.has_user(new_coach))
     # check that the coach has been enrolled in the ccx
     ccx_course_object = courses.get_course_by_id(self.ccx_key)
     self.assertTrue(
         CourseEnrollment.objects.filter(course_id=ccx_course_object.id, user=new_coach).exists()
     )
     # check that an email has been sent to the coach
     self.assertEqual(len(outbox), 1)
     self.assertIn(new_coach.email, outbox[0].recipients())  # pylint: disable=no-member
    def _user_factory_with_history(self, is_staff=False, set_initial_history=True):
        """
        Helper method to generate either an Admin or a User
        """
        if is_staff:
            user = AdminFactory()
        else:
            user = UserFactory()

        user.date_joined = timezone.now()

        if set_initial_history:
            history = PasswordHistory()
            history.create(user)

        return user
Example #13
0
    def _test_add_histogram(self):
        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password='******')

        course = CourseFactory.create(org='test',
            number='313', display_name='histogram test')
        section = ItemFactory.create(
            parent_location=course.location, display_name='chapter hist',
            category='chapter')
        problem = ItemFactory.create(
            parent_location=section.location, display_name='problem hist 1',
            category='problem')
        problem.has_score = False  # don't trip trying to retrieve db data

        late_problem = ItemFactory.create(
            parent_location=section.location, display_name='problem hist 2',
            category='problem')
        late_problem.start = datetime.datetime.now(UTC) + datetime.timedelta(days=32)
        late_problem.has_score = False


        problem_module = factories.get_test_xmodule_for_descriptor(problem)
        problem_module.get_html = xmodule_modifiers.add_histogram(lambda:'', problem_module, instructor)

        self.assertRegexpMatches(
            problem_module.get_html(), r'.*<font color=\'green\'>Not yet</font>.*')

        problem_module = factories.get_test_xmodule_for_descriptor(late_problem)
        problem_module.get_html = xmodule_modifiers.add_histogram(lambda: '', problem_module, instructor)

        self.assertRegexpMatches(
            problem_module.get_html(), r'.*<font color=\'red\'>Yes!</font>.*')
    def setUp(self):
        super(TestGetProblemGradeDistribution, self).setUp()

        self.request_factory = RequestFactory()
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password='******')
        self.attempts = 3
        self.course = CourseFactory.create(
            display_name=u"test course omega \u03a9",
        )

        section = ItemFactory.create(
            parent_location=self.course.location,
            category="chapter",
            display_name=u"test factory section omega \u03a9",
        )
        self.sub_section = ItemFactory.create(
            parent_location=section.location,
            category="sequential",
            display_name=u"test subsection omega \u03a9",
        )

        unit = ItemFactory.create(
            parent_location=self.sub_section.location,
            category="vertical",
            metadata={'graded': True, 'format': 'Homework'},
            display_name=u"test unit omega \u03a9",
        )

        self.users = [UserFactory.create(username="******" + str(__)) for __ in xrange(USER_COUNT)]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i in xrange(USER_COUNT - 1):
            category = "problem"
            self.item = ItemFactory.create(
                parent_location=unit.location,
                category=category,
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'},
                display_name=u"test problem omega \u03a9 " + str(i)
            )

            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    grade=1 if i < j else 0,
                    max_grade=1 if i < j else 0.5,
                    student=user,
                    course_id=self.course.id,
                    module_state_key=self.item.location,
                    state=json.dumps({'attempts': self.attempts}),
                )

            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    course_id=self.course.id,
                    module_type='sequential',
                    module_state_key=self.item.location,
                )
Example #15
0
    def setUp(self):
        """
        Set up courses and enrollments.
        """
        super(TestStudentViewsWithCCX, self).setUp()

        # Create a Draft Mongo and a Split Mongo course and enroll a student user in them.
        self.student_password = "******"
        self.student = UserFactory.create(username="******", password=self.student_password, is_staff=False)
        self.draft_course = SampleCourseFactory.create(default_store=ModuleStoreEnum.Type.mongo)
        self.split_course = SampleCourseFactory.create(default_store=ModuleStoreEnum.Type.split)
        CourseEnrollment.enroll(self.student, self.draft_course.id)
        CourseEnrollment.enroll(self.student, self.split_course.id)

        # Create a CCX coach.
        self.coach = AdminFactory.create()
        role = CourseCcxCoachRole(self.split_course.id)
        role.add_users(self.coach)

        # Create a CCX course and enroll the user in it.
        self.ccx = CcxFactory(course_id=self.split_course.id, coach=self.coach)
        last_week = datetime.datetime.now(UTC()) - datetime.timedelta(days=7)
        override_field_for_ccx(self.ccx, self.split_course, 'start', last_week)  # Required by self.ccx.has_started().
        self.ccx_course_key = CCXLocator.from_course_locator(self.split_course.id, self.ccx.id)
        CourseEnrollment.enroll(self.student, self.ccx_course_key)
    def setUp(self):
        super(TestGradebook, self).setUp()

        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password='******')
        self.users = [UserFactory.create() for _ in xrange(USER_COUNT)]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i, item in enumerate(self.items):
            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    grade=1 if i < j else 0,
                    max_grade=1,
                    student=user,
                    course_id=self.course.id,
                    module_state_key=item.location
                )

        self.response = self.client.get(reverse(
            'spoc_gradebook',
            args=(self.course.id.to_deprecated_string(),)
        ))

        self.assertEquals(self.response.status_code, 200)
Example #17
0
 def setUp(self):
     super(TestRenderMessageToString, self).setUp()
     coach = AdminFactory.create()
     role = CourseCcxCoachRole(self.course.id)
     role.add_users(coach)
     self.ccx = CcxFactory(course_id=self.course.id, coach=coach)
     self.course_key = CCXLocator.from_course_locator(self.course.id, self.ccx.id)
Example #18
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestCoachDashboard, self).setUp()
        self.course = course = CourseFactory.create()

        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create a course outline
        self.mooc_start = start = datetime.datetime(
            2010, 5, 12, 2, 42, tzinfo=pytz.UTC)
        self.mooc_due = due = datetime.datetime(
            2010, 7, 7, 0, 0, tzinfo=pytz.UTC)
        chapters = [ItemFactory.create(start=start, parent=course)
                    for _ in xrange(2)]
        sequentials = flatten([
            [
                ItemFactory.create(parent=chapter) for _ in xrange(2)
            ] for chapter in chapters
        ])
        verticals = flatten([
            [
                ItemFactory.create(
                    due=due, parent=sequential, graded=True, format='Homework'
                ) for _ in xrange(2)
            ] for sequential in sequentials
        ])
        blocks = flatten([  # pylint: disable=unused-variable
            [
                ItemFactory.create(parent=vertical) for _ in xrange(2)
            ] for vertical in verticals
        ])
Example #19
0
 def setUp(self):
     super(DiscussionTabTestCase, self).setUp()
     self.course = CourseFactory.create()
     self.enrolled_user = UserFactory.create()
     self.staff_user = AdminFactory.create()
     CourseEnrollmentFactory.create(user=self.enrolled_user, course_id=self.course.id)
     self.unenrolled_user = UserFactory.create()
    def setUp(self):
        """
        Set up tests
        """
        super(TestFieldOverrides, self).setUp()
        self.course = course = CourseFactory.create()
        self.course.enable_ccx = True

        # Create a course outline
        self.mooc_start = start = datetime.datetime(
            2010, 5, 12, 2, 42, tzinfo=pytz.UTC)
        self.mooc_due = due = datetime.datetime(
            2010, 7, 7, 0, 0, tzinfo=pytz.UTC)
        chapters = [ItemFactory.create(start=start, parent=course)
                    for _ in xrange(2)]
        sequentials = flatten([
            [ItemFactory.create(parent=chapter) for _ in xrange(2)]
            for chapter in chapters])
        verticals = flatten([
            [ItemFactory.create(due=due, parent=sequential) for _ in xrange(2)]
            for sequential in sequentials])
        blocks = flatten([  # pylint: disable=unused-variable
            [ItemFactory.create(parent=vertical) for _ in xrange(2)]
            for vertical in verticals])

        self.ccx = ccx = CustomCourseForEdX(
            course_id=course.id,
            display_name='Test CCX',
            coach=AdminFactory.create())
        ccx.save()

        patch = mock.patch('ccx.overrides.get_current_ccx')
        self.get_ccx = get_ccx = patch.start()
        get_ccx.return_value = ccx
        self.addCleanup(patch.stop)

        self.addCleanup(RequestCache.clear_request_cache)

        inject_field_overrides(iter_blocks(ccx.course), course, AdminFactory.create())

        def cleanup_provider_classes():
            """
            After everything is done, clean up by un-doing the change to the
            OverrideFieldData object that is done during the wrap method.
            """
            OverrideFieldData.provider_classes = None
        self.addCleanup(cleanup_provider_classes)
Example #21
0
    def setUp(self):
        super(TeamAPITestCase, self).setUp()

        teams_configuration = {
            'topics':
            [
                {
                    'id': 'topic_{}'.format(i),
                    'name': name,
                    'description': 'Description for topic {}.'.format(i)
                } for i, name in enumerate([u'sólar power', 'Wind Power', 'Nuclear Power', 'Coal Power'])
            ]
        }
        self.topics_count = 4

        self.test_course_1 = CourseFactory.create(
            org='TestX',
            course='TS101',
            display_name='Test Course',
            teams_configuration=teams_configuration
        )
        self.test_course_2 = CourseFactory.create(org='MIT', course='6.002x', display_name='Circuits')

        self.users = {
            'student_unenrolled': UserFactory.create(password=self.test_password),
            'student_enrolled': UserFactory.create(password=self.test_password),
            'student_enrolled_not_on_team': UserFactory.create(password=self.test_password),

            # This student is enrolled in both test courses and is a member of a team in each course, but is not on the
            # same team as student_enrolled.
            'student_enrolled_both_courses_other_team': UserFactory.create(password=self.test_password),

            'staff': AdminFactory.create(password=self.test_password),
            'course_staff': StaffFactory.create(course_key=self.test_course_1.id, password=self.test_password)
        }
        # 'solar team' is intentionally lower case to test case insensitivity in name ordering
        self.test_team_1 = CourseTeamFactory.create(
            name=u'sólar team',
            course_id=self.test_course_1.id,
            topic_id='topic_0'
        )
        self.test_team_2 = CourseTeamFactory.create(name='Wind Team', course_id=self.test_course_1.id)
        self.test_team_3 = CourseTeamFactory.create(name='Nuclear Team', course_id=self.test_course_1.id)
        self.test_team_4 = CourseTeamFactory.create(name='Coal Team', course_id=self.test_course_1.id, is_active=False)
        self.test_team_5 = CourseTeamFactory.create(name='Another Team', course_id=self.test_course_2.id)

        for user, course in [
                ('student_enrolled', self.test_course_1),
                ('student_enrolled_not_on_team', self.test_course_1),
                ('student_enrolled_both_courses_other_team', self.test_course_1),
                ('student_enrolled_both_courses_other_team', self.test_course_2)
        ]:
            CourseEnrollment.enroll(
                self.users[user], course.id, check_access=True
            )

        self.test_team_1.add_user(self.users['student_enrolled'])
        self.test_team_3.add_user(self.users['student_enrolled_both_courses_other_team'])
        self.test_team_5.add_user(self.users['student_enrolled_both_courses_other_team'])
Example #22
0
    def setUp(self):
        self.course = CourseFactory.create()
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password="******")

        # load initial content (since we don't run migrations as part of tests):
        call_command("loaddata", "course_email_template.json")
        self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id})
Example #23
0
 def setUp(self):
     """Set up a course, coach, ccx and user"""
     super(TestGetMembershipTriplets, self).setUp()
     self.course = CourseFactory.create()
     coach = AdminFactory.create()
     role = CourseCcxCoachRole(self.course.id)
     role.add_users(coach)
     self.ccx = CcxFactory(course_id=self.course.id, coach=coach)
Example #24
0
    def setUp(self):
        self.instructor = AdminFactory.create()
        self.course = CourseFactory.create()
        self.client.login(username=self.instructor.username, password='******')

        self.students = [UserFactory() for _ in xrange(6)]
        for student in self.students:
            CourseEnrollment.enroll(student, self.course.id)
Example #25
0
 def setUp(self):
     """common setup for all tests"""
     super(TestCCX, self).setUp()
     self.course = course = CourseFactory.create()
     coach = AdminFactory.create()
     role = CourseCcxCoachRole(course.id)
     role.add_users(coach)
     self.ccx = CcxFactory(course_id=course.id, coach=coach)
    def setUp(self):
        super(TestProctoringDashboardViews, self).setUp()

        # Create instructor account
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password="******")

        CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
    def setUp(self):
        super(TestGradebookVertical, self).setUp()

        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password='******')

        # remove the caches
        modulestore().request_cache = None
        modulestore().metadata_inheritance_cache_subsystem = None

        kwargs = {}
        if self.grading_policy is not None:
            kwargs['grading_policy'] = self.grading_policy

        self.course = CourseFactory.create(**kwargs)
        chapter = ItemFactory.create(
            parent_location=self.course.location,
            category="sequential",
        )
        section = ItemFactory.create(
            parent_location=chapter.location,
            category="vertical",
            metadata={'graded': True, 'format': 'Homework', 'weight': 0.8}
        )

        ItemFactory.create(
            parent_location=chapter.location,
            category="vertical",
            metadata={'graded': True, 'format': 'Homework', 'weight': 0.2}
        )

        self.users = [UserFactory.create() for _ in xrange(USER_COUNT)]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i in xrange(USER_COUNT - 1):
            category = "problem"
            item = ItemFactory.create(
                parent_location=section.location,
                category=category,
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'}
            )

            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    grade=1 if i < j else 0,
                    max_grade=1,
                    student=user,
                    course_id=self.course.id,
                    module_state_key=item.location
                )

        self.response = self.client.get(reverse(
            'spoc_gradebook',
            args=(self.course.id.to_deprecated_string(),)
        ))
 def setUp(self):
     """
     Log in as an instructor, and create a course/student to reset.
     """
     instructor = AdminFactory.create()
     self.client.login(username=instructor.username, password='******')
     self.student = UserFactory.create(username='******', email='*****@*****.**')
     self.course = CourseFactory.create()
     CourseEnrollmentFactory.create(user=self.student, course_id=self.course.id)
    def make_instructor(self):
        """
        create staff instructor
        """
        instructor = AdminFactory.create(password="******")
        role = CourseInstructorRole(self.course.id)
        role.add_users(instructor)

        return instructor
    def make_staff(self):
        """
        create staff user
        """
        staff = AdminFactory.create(password="******")
        role = CourseStaffRole(self.course.id)
        role.add_users(staff)

        return staff
Example #31
0
    def test_closed_course_admin(self):
        """
        Users marked as Admin should be able to submit grade events to a closed course
        """
        self.user = AdminFactory()
        course = self.setup_course_with_grading(
            start=datetime(2010, 1, 1, tzinfo=UTC()),
            end=datetime(2011, 1, 1, tzinfo=UTC()),
        )
        module = self.get_module_for_user(self.user, course,
                                          course.homework_assignment)
        grade_dict = {'value': 0.5, 'max_value': 1, 'user_id': self.user.id}
        module.system.publish(module, 'grade', grade_dict)

        with self.assertRaises(StudentGradebook.DoesNotExist):
            __ = StudentGradebook.objects.get(user=self.user,
                                              course_id=course.id)

        gradebook = StudentGradebook.objects.all()
        self.assertEqual(len(gradebook), 0)

        history = StudentGradebookHistory.objects.all()
        self.assertEqual(len(history), 0)
Example #32
0
    def test_submission_history_xss(self):
        # log into a staff account
        admin = AdminFactory()

        self.client.login(username=admin.username, password='******')

        # try it with an existing user and a malicious location
        url = reverse('submission_history', kwargs={
            'course_id': self.course_key.to_deprecated_string(),
            'student_username': '******',
            'location': '<script>alert("hello");</script>'
        })
        response = self.client.get(url)
        self.assertFalse('<script>' in response.content)

        # try it with a malicious user and a non-existent location
        url = reverse('submission_history', kwargs={
            'course_id': self.course_key.to_deprecated_string(),
            'student_username': '******',
            'location': 'dummy'
        })
        response = self.client.get(url)
        self.assertFalse('<script>' in response.content)
Example #33
0
    def setUp(self):
        super(TestGradebook, self).setUp()

        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password='******')
        self.users = [UserFactory.create() for _ in xrange(USER_COUNT)]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i, item in enumerate(self.items):
            for j, user in enumerate(self.users):
                StudentModuleFactory.create(grade=1 if i < j else 0,
                                            max_grade=1,
                                            student=user,
                                            course_id=self.course.id,
                                            module_state_key=item.location)

        self.response = self.client.get(
            reverse('spoc_gradebook',
                    args=(self.course.id.to_deprecated_string(), )))

        self.assertEquals(self.response.status_code, 200)
Example #34
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestInstructorDashboard, self).setUp()
        self.course = CourseFactory.create(
            grading_policy={"GRADE_CUTOFFS": {"A": 0.75, "B": 0.63, "C": 0.57, "D": 0.5}},
            display_name='<script>alert("XSS")</script>'
        )

        self.course_mode = CourseMode(
            course_id=self.course.id,
            mode_slug=CourseMode.DEFAULT_MODE_SLUG,
            mode_display_name=CourseMode.DEFAULT_MODE.name,
            min_price=40
        )
        self.course_mode.save()
        # Create instructor account
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password="******")

        # URL for instructor dash
        self.url = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})
Example #35
0
    def setUp(self):
        super(TestOptoutCourseEmails, self).setUp()
        course_title = u"ẗëṡẗ title イ乇丂イ ᄊ乇丂丂ムg乇 キo尺 ムレレ тэѕт мэѕѕаБэ"
        self.course = CourseFactory.create(run='testcourse1',
                                           display_name=course_title)
        self.instructor = AdminFactory.create()
        self.student = UserFactory.create()
        CourseEnrollmentFactory.create(user=self.student,
                                       course_id=self.course.id)

        # load initial content (since we don't run migrations as part of tests):
        call_command("loaddata", "course_email_template.json")

        self.client.login(username=self.student.username, password="******")

        self.send_mail_url = reverse(
            'send_email', kwargs={'course_id': text_type(self.course.id)})
        self.success_content = {
            'course_id': text_type(self.course.id),
            'success': True,
        }
        BulkEmailFlag.objects.create(enabled=True,
                                     require_course_email_auth=False)
Example #36
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestCCXGrades, self).setUp()

        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create CCX
        role = CourseCcxCoachRole(self._course.id)
        role.add_users(coach)
        ccx = CcxFactory(course_id=self._course.id, coach=self.coach)

        # override course grading policy and make last section invisible to students
        override_field_for_ccx(ccx, self._course, 'grading_policy', {
            'GRADER': [
                {'drop_count': 0,
                 'min_count': 2,
                 'short_label': 'HW',
                 'type': 'Homework',
                 'weight': 1}
            ],
            'GRADE_CUTOFFS': {'Pass': 0.75},
        })
        override_field_for_ccx(
            ccx, self.sections[-1], 'visible_to_staff_only', True
        )

        # create a ccx locator and retrieve the course structure using that key
        # which emulates how a student would get access.
        self.ccx_key = CCXLocator.from_course_locator(self._course.id, ccx.id)
        self.course = get_course_by_id(self.ccx_key, depth=None)
        setup_students_and_grades(self)
        self.client.login(username=coach.username, password="******")
        self.addCleanup(RequestCache.clear_request_cache)
Example #37
0
    def _test_add_histogram(self):
        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password='******')

        course = CourseFactory.create(org='test',
                                      number='313',
                                      display_name='histogram test')
        section = ItemFactory.create(parent_location=course.location,
                                     display_name='chapter hist',
                                     category='chapter')
        problem = ItemFactory.create(parent_location=section.location,
                                     display_name='problem hist 1',
                                     category='problem')
        problem.has_score = False  # don't trip trying to retrieve db data

        late_problem = ItemFactory.create(parent_location=section.location,
                                          display_name='problem hist 2',
                                          category='problem')
        late_problem.lms.start = datetime.datetime.now(
            UTC) + datetime.timedelta(days=32)
        late_problem.has_score = False

        problem_module = factories.get_test_xmodule_for_descriptor(problem)
        problem_module.get_html = xmodule_modifiers.add_histogram(
            lambda: '', problem_module, instructor)

        self.assertRegexpMatches(problem_module.get_html(),
                                 r'.*<font color=\'green\'>Not yet</font>.*')

        problem_module = factories.get_test_xmodule_for_descriptor(
            late_problem)
        problem_module.get_html = xmodule_modifiers.add_histogram(
            lambda: '', problem_module, instructor)

        self.assertRegexpMatches(problem_module.get_html(),
                                 r'.*<font color=\'red\'>Yes!</font>.*')
    def setUp(self):
        super(TestGradebook, self).setUp()

        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password='******')
        self.users = [UserFactory.create() for _ in range(USER_COUNT)]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i, item in enumerate(self.items):
            for j, user in enumerate(self.users):
                StudentModuleFactory.create(grade=1 if i < j else 0,
                                            max_grade=1,
                                            student=user,
                                            course_id=self.course.id,
                                            module_state_key=item.location)
        task_compute_all_grades_for_course.apply_async(
            kwargs={'course_key': text_type(self.course.id)})

        self.response = self.client.get(
            reverse('spoc_gradebook', args=(text_type(self.course.id), )))

        self.assertEqual(self.response.status_code, 200)
Example #39
0
    def create_user_for_course(self,
                               course,
                               user_type=CourseUserType.ENROLLED):
        """
        Create a test user for a course.
        """
        if user_type is CourseUserType.ANONYMOUS:
            return AnonymousUser()

        is_enrolled = user_type is CourseUserType.ENROLLED
        is_unenrolled_staff = user_type is CourseUserType.UNENROLLED_STAFF

        # Set up the test user
        if is_unenrolled_staff:
            user = StaffFactory(course_key=course.id,
                                password=self.TEST_PASSWORD)
        elif user_type is CourseUserType.GLOBAL_STAFF:
            user = AdminFactory(password=self.TEST_PASSWORD)
        else:
            user = UserFactory(password=self.TEST_PASSWORD)
        self.client.login(username=user.username, password=self.TEST_PASSWORD)
        if is_enrolled:
            CourseEnrollment.enroll(user, course.id)
        return user
Example #40
0
    def _load_mktg_about(self, language=None):
        """
        Retrieve the marketing about button (iframed into the marketing site)
        and return the HTTP response.

        Keyword Args:
            language (string): If provided, send this in the 'Accept-Language' HTTP header.

        Returns:
            Response

        """
        # Log in as an administrator to guarantee that we can access the button
        admin = AdminFactory()
        self.client.login(username=admin.username, password='******')

        # If provided, set the language header
        headers = {}
        if language is not None:
            headers['HTTP_ACCEPT_LANGUAGE'] = language

        url = reverse('mktg_about_course',
                      kwargs={'course_id': unicode(self.course_key)})
        return self.client.get(url, **headers)
Example #41
0
 def setUp(self):
     super(CourseRunViewSetTests, self).setUp()
     self.client = APIClient()
     user = AdminFactory()
     self.client.login(username=user.username, password=TEST_PASSWORD)
Example #42
0
    def setUp(self):
        super(TestNewInstructorDashboardEmailViewMongoBacked, self).setUp()

        # Create instructor account
        instructor = AdminFactory.create()
        self.client.login(username=instructor.username, password="******")
Example #43
0
 def setUp(self):
     """ Test case setup """
     self.global_admin = AdminFactory()
     self.creator = User.objects.create_user('testcreator', '*****@*****.**', 'foo')
     self.staff = User.objects.create_user('teststaff', '*****@*****.**', 'foo')
     self.location = Location('i4x', 'mitX', '101', 'course', 'test')
Example #44
0
 def _verify_cohort_settings_response(self, expected_response):
     request = RequestFactory().get("dummy_url")
     request.user = AdminFactory()
     response = cohorting_settings(request, unicode(self.course.id))
     self.assertEqual(200, response.status_code)
     self.assertEqual(expected_response, json.loads(response.content))
Example #45
0
    def test_full_query_no_completions(self):
        start = timezone.now()
        client = APIClient()
        print("CREATING USERS", timezone.now())
        admin = AdminFactory.create(username='******', password='******')
        users = []
        one_percent = self.user_count / 100
        for i in range(self.user_count):
            users.append(User(username='******'.format(i)))
            if i % one_percent == one_percent - 1:
                print('.', end='')
                sys.stdout.flush()
            #users.append(UserFactory.create())
        User.objects.bulk_create(users)
        print("CREATING ENROLLMENTS AND AGGREGATORS", timezone.now())
        enrollments = []
        aggs = []
        for i, user in enumerate(users):
            if i % one_percent == one_percent - 1:
                print('.', end='')
                sys.stdout.flush()
            enrollments.append(
                CourseEnrollment(user=user, course_id=self.course.id))
            aggs.append(
                Aggregator(
                    user=user,
                    course_key=self.course.id,
                    block_key=self.course.mapped_location,
                    aggregation_name='course',
                    earned=576.0,
                    possible=1044.0,
                    percent=0.4,
                    last_modified=start,
                ))
            for chapter in self.chapters:
                aggs.append(
                    Aggregator(
                        user=user,
                        course_key=self.course.id,
                        block_key=chapter.mapped_location,
                        aggregation_name='chapter',
                        earned=72.0,
                        possible=180.0,
                        percent=0.4,
                        last_modified=start,
                    ))
            continue
            for sequential in self.sequentials:
                aggs.append(
                    Aggregator(
                        user=user,
                        course_key=self.course.id,
                        block_key=sequential.mapped_location,
                        aggregation_name='sequential',
                        earned=24.0,
                        possible=60.0,
                        percent=0.4,
                        last_modified=start,
                    ))
            for vertical in self.verticals:
                aggs.append(
                    Aggregator(
                        user=user,
                        course_key=self.course.id,
                        block_key=vertical.mapped_location,
                        aggregation_name='vertical',
                        earned=2.0,
                        possible=5.0,
                        percent=0.4,
                        last_modified=start,
                    ))
        print("Enrollments:", len(enrollments))
        print("Aggregators:", len(aggs))
        CourseEnrollment.objects.bulk_create(enrollments, batch_size=500)
        Aggregator.objects.bulk_create(aggs, batch_size=500)
        client.login(username='******', password='******')
        startquery = timezone.now()
        print("START", startquery)
        results = []

        url = '/api/completion-aggregator/v1/course/{}/?page_size={}&requested_fields=chapter'.format(
            self.course.id, self.page_size)
        url = '/api/completion-aggregator/v1/course/{}/?page_size={}'.format(
            self.course.id, self.page_size)
        response = client.get(url)
        self.assertEqual(len(response.data['results']), self.page_size)
        results.extend(response.data['results'])
        print(connection.queries)
        print("  ", response.data['pagination'], timezone.now())
        while response.data['pagination']['next']:
            response = client.get(response.data['pagination']['next'])
            print("  ", response.data['pagination'], timezone.now())
            results.extend(response.data['results'])
        endquery = timezone.now()
        print('End collection', endquery)
        self.assertEqual(len(results), self.user_count)
        print("Query run time: {}s".format(
            (endquery - startquery).total_seconds()))
        print(results[:10])
        self.assertLess(endquery - startquery, timedelta(seconds=128))
        self.assertLess(endquery - startquery, timedelta(seconds=64))
        self.assertLess(endquery - startquery, timedelta(seconds=32))
        self.assertLess(endquery - startquery, timedelta(seconds=16))
        self.assertLess(endquery - startquery, timedelta(seconds=8))
Example #46
0
    def setUp(self):
        super(CourseAboutTestCaseCCX, self).setUp()

        # Create ccx coach account
        self.coach = coach = AdminFactory.create(password="******")
        self.client.login(username=coach.username, password="******")
Example #47
0
 def setUp(self):
     self.instructor = AdminFactory.create()
     self.course = CourseFactory.create()
     self.client.login(username=self.instructor.username, password='******')
Example #48
0
 def test_no_user_staff_all_blocks(self):
     self.client.login(username=AdminFactory.create().username,
                       password='******')
     self.query_params.pop('username')
     self.query_params['all_blocks'] = True
     self.verify_response()
Example #49
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestCCXGrades, self).setUp()

        self._course = CourseFactory.create(enable_ccx=True)

        # Create a course outline
        self.start = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=pytz.UTC)
        chapter = ItemFactory.create(start=self.start,
                                     parent=self._course,
                                     category='sequential')
        self.sections = [
            ItemFactory.create(parent=chapter,
                               category="sequential",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework'
                               }) for _ in xrange(4)
        ]
        # making problems available at class level for possible future use in tests
        self.problems = [[
            ItemFactory.create(
                parent=section,
                category="problem",
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'}) for _ in xrange(4)
        ] for section in self.sections]

        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create CCX
        role = CourseCcxCoachRole(self._course.id)
        role.add_users(coach)
        ccx = CcxFactory(course_id=self._course.id, coach=self.coach)

        # override course grading policy and make last section invisible to students
        override_field_for_ccx(
            ccx, self._course, 'grading_policy', {
                'GRADER': [{
                    'drop_count': 0,
                    'min_count': 2,
                    'short_label': 'HW',
                    'type': 'Homework',
                    'weight': 1
                }],
                'GRADE_CUTOFFS': {
                    'Pass': 0.75
                },
            })
        override_field_for_ccx(ccx, self.sections[-1], 'visible_to_staff_only',
                               True)

        # create a ccx locator and retrieve the course structure using that key
        # which emulates how a student would get access.
        self.ccx_key = CCXLocator.from_course_locator(self._course.id, ccx.id)
        self.course = get_course_by_id(self.ccx_key, depth=None)
        setup_students_and_grades(self)
        self.client.login(username=coach.username, password="******")
        self.addCleanup(RequestCache.clear_request_cache)
Example #50
0
 def test_staff_can_view_all(self):
     """ Verify that staff users can view eligibility data for all users. """
     staff = AdminFactory(password=self.password)
     self.client.logout()
     self.client.login(username=staff.username, password=self.password)
     self.assert_valid_get_response(self.eligibility)
Example #51
0
    def setUp(self):
        super(TestGetProblemGradeDistribution, self).setUp()

        self.request_factory = RequestFactory()
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password='******')
        self.attempts = 3
        self.users = [
            UserFactory.create(username="******" + str(__))
            for __ in xrange(USER_COUNT)
        ]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        #  Adding an instructor and a staff to the site.  These should not be included in any reports.
        instructor_member = InstructorFactory(course_key=self.course.id)
        CourseEnrollment.enroll(instructor_member, self.course.id)

        staff_member = StaffFactory(course_key=self.course.id)
        CourseEnrollment.enroll(staff_member, self.course.id)

        for i, item in enumerate(self.items):
            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    grade=1 if i < j else 0,
                    max_grade=1,
                    student=user,
                    course_id=self.course.id,
                    module_state_key=item.location,
                    state=json.dumps({'attempts': self.attempts}),
                )

            StudentModuleFactory.create(
                grade=1,
                max_grade=1,
                student=instructor_member,
                course_id=self.course.id,
                module_state_key=item.location,
                state=json.dumps({'attempts': self.attempts}),
            )

            StudentModuleFactory.create(
                grade=1,
                max_grade=1,
                student=staff_member,
                course_id=self.course.id,
                module_state_key=item.location,
                state=json.dumps({'attempts': self.attempts}),
            )

        for j, user in enumerate(self.users):
            StudentModuleFactory.create(
                course_id=self.course.id,
                student=user,
                module_type='sequential',
                module_state_key=self.sub_section.location,
            )

        StudentModuleFactory.create(
            course_id=self.course.id,
            student=instructor_member,
            module_type='sequential',
            module_state_key=self.sub_section.location,
        )

        StudentModuleFactory.create(
            course_id=self.course.id,
            student=staff_member,
            module_type='sequential',
            module_state_key=self.sub_section.location,
        )
Example #52
0
 def setUp(self):
     super(MaintenanceViewTestCase, self).setUp()
     self.user = AdminFactory()
     login_success = self.client.login(username=self.user.username,
                                       password='******')
     self.assertTrue(login_success)
    def setUp(self):
        """
        Set up tests
        """
        super(TestCCXGrades, self).setUp()
        self.course = course = CourseFactory.create()

        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create a course outline
        self.mooc_start = start = datetime.datetime(2010,
                                                    5,
                                                    12,
                                                    2,
                                                    42,
                                                    tzinfo=pytz.UTC)
        chapter = ItemFactory.create(start=start,
                                     parent=course,
                                     category='sequential')
        sections = [
            ItemFactory.create(parent=chapter,
                               category="sequential",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework'
                               }) for _ in xrange(4)
        ]

        role = CourseCcxCoachRole(self.course.id)
        role.add_users(coach)
        self.ccx = ccx = CcxFactory(course_id=self.course.id, coach=self.coach)

        self.student = student = UserFactory.create()
        CourseEnrollmentFactory.create(user=student, course_id=self.course.id)
        CcxMembershipFactory(ccx=ccx, student=student, active=True)

        for i, section in enumerate(sections):
            for j in xrange(4):
                item = ItemFactory.create(
                    parent=section,
                    category="problem",
                    data=StringResponseXMLFactory().build_xml(answer='foo'),
                    metadata={'rerandomize': 'always'})

                StudentModuleFactory.create(grade=1 if i < j else 0,
                                            max_grade=1,
                                            student=student,
                                            course_id=self.course.id,
                                            module_state_key=item.location)

        # Apparently the test harness doesn't use LmsFieldStorage, and I'm not
        # sure if there's a way to poke the test harness to do so.  So, we'll
        # just inject the override field storage in this brute force manner.
        OverrideFieldData.provider_classes = None
        # pylint: disable=protected-access
        for block in iter_blocks(course):
            block._field_data = OverrideFieldData.wrap(coach,
                                                       block._field_data)
            new_cache = {'tabs': [], 'discussion_topics': []}
            if 'grading_policy' in block._field_data_cache:
                new_cache['grading_policy'] = block._field_data_cache[
                    'grading_policy']
            block._field_data_cache = new_cache

        def cleanup_provider_classes():
            """
            After everything is done, clean up by un-doing the change to the
            OverrideFieldData object that is done during the wrap method.
            """
            OverrideFieldData.provider_classes = None

        self.addCleanup(cleanup_provider_classes)

        patch_context = patch('ccx.views.get_course_by_id')
        get_course = patch_context.start()
        get_course.return_value = course
        self.addCleanup(patch_context.stop)

        override_field_for_ccx(
            ccx, course, 'grading_policy', {
                'GRADER': [{
                    'drop_count': 0,
                    'min_count': 2,
                    'short_label': 'HW',
                    'type': 'Homework',
                    'weight': 1
                }],
                'GRADE_CUTOFFS': {
                    'Pass': 0.75
                },
            })
        override_field_for_ccx(ccx, sections[-1], 'visible_to_staff_only',
                               True)
Example #54
0
    def setUp(self):
        """
        Set up tests
        """
        super(TestCCXGrades, self).setUp()
        self.course = course = CourseFactory.create(enable_ccx=True)

        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create a course outline
        self.mooc_start = start = datetime.datetime(2010,
                                                    5,
                                                    12,
                                                    2,
                                                    42,
                                                    tzinfo=pytz.UTC)
        chapter = ItemFactory.create(start=start,
                                     parent=course,
                                     category='sequential')
        sections = [
            ItemFactory.create(parent=chapter,
                               category="sequential",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework'
                               }) for _ in xrange(4)
        ]
        # pylint: disable=unused-variable
        problems = [[
            ItemFactory.create(
                parent=section,
                category="problem",
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'}) for _ in xrange(4)
        ] for section in sections]

        # Create CCX
        role = CourseCcxCoachRole(course.id)
        role.add_users(coach)
        ccx = CcxFactory(course_id=course.id, coach=self.coach)

        # override course grading policy and make last section invisible to students
        override_field_for_ccx(
            ccx, course, 'grading_policy', {
                'GRADER': [{
                    'drop_count': 0,
                    'min_count': 2,
                    'short_label': 'HW',
                    'type': 'Homework',
                    'weight': 1
                }],
                'GRADE_CUTOFFS': {
                    'Pass': 0.75
                },
            })
        override_field_for_ccx(ccx, sections[-1], 'visible_to_staff_only',
                               True)

        # create a ccx locator and retrieve the course structure using that key
        # which emulates how a student would get access.
        self.ccx_key = CCXLocator.from_course_locator(course.id, ccx.id)
        self.course = get_course_by_id(self.ccx_key)

        self.student = student = UserFactory.create()
        CourseEnrollmentFactory.create(user=student, course_id=self.course.id)
        CcxMembershipFactory(ccx=ccx, student=student, active=True)

        # create grades for self.student as if they'd submitted the ccx
        for chapter in self.course.get_children():
            for i, section in enumerate(chapter.get_children()):
                for j, problem in enumerate(section.get_children()):
                    # if not problem.visible_to_staff_only:
                    StudentModuleFactory.create(
                        grade=1 if i < j else 0,
                        max_grade=1,
                        student=self.student,
                        course_id=self.course.id,
                        module_state_key=problem.location)

        self.client.login(username=coach.username, password="******")

        self.addCleanup(RequestCache.clear_request_cache)
Example #55
0
 def setUp(self):
     super(TestMaintenanceIndex, self).setUp()
     self.user = AdminFactory()
     login_success = self.client.login(username=self.user.username, password='******')
     self.assertTrue(login_success)
     self.view_url = reverse('maintenance:maintenance_index')
Example #56
0
 def setUp(self):
     super(WikiTabTestCase, self).setUp()
     self.course = CourseFactory.create()
     self.instructor = AdminFactory.create()
     self.user = UserFactory()
Example #57
0
    def setUp(self):
        """
        Set up a course with graded problems.

        Course hierarchy is as follows:
        -> course
            -> chapter
                -> vertical (graded)
                    -> problem
                    -> problem
        """
        super(TestCCXGradesVertical, self).setUp()
        self.course = course = CourseFactory.create(enable_ccx=True)
        # Create instructor account
        self.coach = coach = AdminFactory.create()
        self.client.login(username=coach.username, password="******")

        # Create a course outline
        self.mooc_start = start = datetime.datetime(2010,
                                                    5,
                                                    12,
                                                    2,
                                                    42,
                                                    tzinfo=pytz.UTC)
        chapter = ItemFactory.create(start=start, parent=course)
        verticals = [
            ItemFactory.create(parent=chapter,
                               category="vertical",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework',
                                   'weight': 0.5
                               }),
            ItemFactory.create(parent=chapter,
                               category="vertical",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework',
                                   'weight': 0.2
                               }),
            ItemFactory.create(parent=chapter,
                               category="vertical",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework',
                                   'weight': 0.2
                               }),
            ItemFactory.create(parent=chapter,
                               category="vertical",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework',
                                   'weight': 0.1
                               }),
            ItemFactory.create(parent=chapter,
                               category="vertical",
                               metadata={
                                   'graded': True,
                                   'format': 'Homework',
                                   'weight': 1.0
                               }),
        ]
        # pylint: disable=unused-variable
        problems = [[
            ItemFactory.create(
                parent=section,
                category="problem",
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'}) for _ in xrange(4)
        ] for section in verticals]

        # Create CCX
        role = CourseCcxCoachRole(course.id)
        role.add_users(coach)
        ccx = CcxFactory(course_id=course.id, coach=self.coach)

        # Apparently the test harness doesn't use LmsFieldStorage, and I'm not
        # sure if there's a way to poke the test harness to do so.  So, we'll
        # just inject the override field storage in this brute force manner.
        OverrideFieldData.provider_classes = None
        # pylint: disable=protected-access
        for block in iter_blocks(course):
            block._field_data = OverrideFieldData.wrap(coach, course,
                                                       block._field_data)
            new_cache = {'tabs': [], 'discussion_topics': []}
            if 'grading_policy' in block._field_data_cache:
                new_cache['grading_policy'] = block._field_data_cache[
                    'grading_policy']
            block._field_data_cache = new_cache

        def cleanup_provider_classes():
            """
            After everything is done, clean up by un-doing the change to the
            OverrideFieldData object that is done during the wrap method.
            """
            OverrideFieldData.provider_classes = None

        self.addCleanup(cleanup_provider_classes)

        # override course grading policy and make last section invisible to students
        override_field_for_ccx(
            ccx, course, 'grading_policy', {
                'GRADER': [{
                    'drop_count': 0,
                    'min_count': 2,
                    'short_label': 'HW',
                    'type': 'Homework',
                    'passing_grade': 0,
                    'weight': 1
                }],
                'GRADE_CUTOFFS': {
                    'Pass': 0.75
                },
            })
        override_field_for_ccx(ccx, verticals[-1], 'visible_to_staff_only',
                               True)

        # create a ccx locator and retrieve the course structure using that key
        # which emulates how a student would get access.
        self.ccx_key = CCXLocator.from_course_locator(course.id, ccx.id)
        self.course = get_course_by_id(self.ccx_key)

        self.student = student = UserFactory.create()
        CourseEnrollmentFactory.create(user=student, course_id=self.course.id)
        CcxMembershipFactory(ccx=ccx, student=student, active=True)

        # create grades for self.student as if they'd submitted the ccx
        for chapter in self.course.get_children():
            for i, vertical in enumerate(chapter.get_children()):
                for j, problem in enumerate(vertical.get_children()):
                    # if not problem.visible_to_staff_only:
                    StudentModuleFactory.create(
                        grade=1 if i < j else 0,
                        max_grade=1,
                        student=self.student,
                        course_id=self.course.id,
                        module_state_key=problem.location)

        self.client.login(username=coach.username, password="******")
    def setUp(self):
        super(TestProctoringDashboardViews, self).setUp()

        # Create instructor account
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password="******")
Example #59
0
    def setUp(self):
        super(TeamAPITestCase, self).setUp()
        self.topics_count = 4
        self.users = {
            'staff': AdminFactory.create(password=self.test_password),
            'course_staff': StaffFactory.create(course_key=self.test_course_1.id, password=self.test_password)
        }
        self.create_and_enroll_student(username='******')
        self.create_and_enroll_student(username='******')
        self.create_and_enroll_student(username='******', courses=[])

        # Make this student a community TA.
        self.create_and_enroll_student(username='******')
        seed_permissions_roles(self.test_course_1.id)
        community_ta_role = Role.objects.get(name=FORUM_ROLE_COMMUNITY_TA, course_id=self.test_course_1.id)
        community_ta_role.users.add(self.users['community_ta'])

        # This student is enrolled in both test courses and is a member of a team in each course, but is not on the
        # same team as student_enrolled.
        self.create_and_enroll_student(
            courses=[self.test_course_1, self.test_course_2],
            username='******'
        )

        # Make this student have a public profile
        self.create_and_enroll_student(
            courses=[self.test_course_2],
            username='******'
        )
        profile = self.users['student_enrolled_public_profile'].profile
        profile.year_of_birth = 1970
        profile.save()

        # 'solar team' is intentionally lower case to test case insensitivity in name ordering
        self.test_team_1 = CourseTeamFactory.create(
            name=u'sólar team',
            course_id=self.test_course_1.id,
            topic_id='topic_0'
        )
        self.test_team_2 = CourseTeamFactory.create(name='Wind Team', course_id=self.test_course_1.id)
        self.test_team_3 = CourseTeamFactory.create(name='Nuclear Team', course_id=self.test_course_1.id)
        self.test_team_4 = CourseTeamFactory.create(name='Coal Team', course_id=self.test_course_1.id, is_active=False)
        self.test_team_5 = CourseTeamFactory.create(name='Another Team', course_id=self.test_course_2.id)
        self.test_team_6 = CourseTeamFactory.create(
            name='Public Profile Team',
            course_id=self.test_course_2.id,
            topic_id='topic_6'
        )

        self.test_team_name_id_map = {team.name: team for team in (
            self.test_team_1,
            self.test_team_2,
            self.test_team_3,
            self.test_team_4,
            self.test_team_5,
        )}

        for user, course in [('staff', self.test_course_1), ('course_staff', self.test_course_1)]:
            CourseEnrollment.enroll(
                self.users[user], course.id, check_access=True
            )

        self.test_team_1.add_user(self.users['student_enrolled'])
        self.test_team_3.add_user(self.users['student_enrolled_both_courses_other_team'])
        self.test_team_5.add_user(self.users['student_enrolled_both_courses_other_team'])
        self.test_team_6.add_user(self.users['student_enrolled_public_profile'])
    def setUp(self):
        super(TestGetProblemGradeDistribution, self).setUp()

        self.request_factory = RequestFactory()
        self.instructor = AdminFactory.create()
        self.client.login(username=self.instructor.username, password='******')
        self.attempts = 3
        self.course = CourseFactory.create(
            display_name=u"test course omega \u03a9", )

        section = ItemFactory.create(
            parent_location=self.course.location,
            category="chapter",
            display_name=u"test factory section omega \u03a9",
        )
        self.sub_section = ItemFactory.create(
            parent_location=section.location,
            category="sequential",
            display_name=u"test subsection omega \u03a9",
        )

        unit = ItemFactory.create(
            parent_location=self.sub_section.location,
            category="vertical",
            metadata={
                'graded': True,
                'format': 'Homework'
            },
            display_name=u"test unit omega \u03a9",
        )

        self.users = [
            UserFactory.create(username="******" + str(__))
            for __ in xrange(USER_COUNT)
        ]

        for user in self.users:
            CourseEnrollmentFactory.create(user=user, course_id=self.course.id)

        for i in xrange(USER_COUNT - 1):
            category = "problem"
            self.item = ItemFactory.create(
                parent_location=unit.location,
                category=category,
                data=StringResponseXMLFactory().build_xml(answer='foo'),
                metadata={'rerandomize': 'always'},
                display_name=u"test problem omega \u03a9 " + str(i))

            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    grade=1 if i < j else 0,
                    max_grade=1 if i < j else 0.5,
                    student=user,
                    course_id=self.course.id,
                    module_state_key=self.item.location,
                    state=json.dumps({'attempts': self.attempts}),
                )

            for j, user in enumerate(self.users):
                StudentModuleFactory.create(
                    course_id=self.course.id,
                    module_type='sequential',
                    module_state_key=self.item.location,
                )