Example #1
0
    def test_display_after_discounted_price(
        self,
        discounted_price,
        is_enterprise_enabled,
        mock_get_course_final_price,
        mock_enterprise_customer_for_request
    ):
        verified_mode = CourseModeFactory.create(mode_slug='verified', course_id=self.course.id, sku='dummy')
        CourseEnrollmentFactory(
            is_active=True,
            course_id=self.course.id,
            user=self.user
        )

        mock_enterprise_customer_for_request.return_value = is_enterprise_enabled
        mock_get_course_final_price.return_value = discounted_price
        url = reverse('course_modes_choose', args=[self.course.id])
        response = self.client.get(url)

        if is_enterprise_enabled:
            self.assertContains(response, discounted_price)
        self.assertContains(response, verified_mode.min_price)
    def test_add_cert_with_existing_pdf_certificate(self):
        """
        Test that add certifcate for existing PDF certificate log warning
        message and certificate status remains unchanged.
        """
        download_url = 'http://www.example.com/certificate.pdf'
        # Create an existing verifed enrollment and certificate
        CourseEnrollmentFactory(
            user=self.user_2,
            course_id=self.course.id,
            is_active=True,
            mode=CourseMode.VERIFIED,
        )
        GeneratedCertificateFactory(user=self.user_2,
                                    course_id=self.course.id,
                                    grade='1.0',
                                    status=CertificateStatuses.downloadable,
                                    mode=GeneratedCertificate.MODES.verified,
                                    download_url=download_url)

        self._assert_pdf_cert_generation_dicontinued_logs(download_url,
                                                          add_cert=True)
Example #3
0
    def test_filter_enrollment_mode(self):
        with patch('lms.djangoapps.grades.course_grade_factory.CourseGradeFactory.read') as mock_grade:
            mock_grade.side_effect = [
                self.mock_course_grade(self.student, passed=True, letter_grade='A', percent=0.85),
                self.mock_course_grade(self.other_student, passed=False, letter_grade=None, percent=0.45),
            ]

            # Enroll a verified student, for whom data should not be returned.
            verified_student = UserFactory()
            _ = CourseEnrollmentFactory(
                course_id=self.course.id,
                user=verified_student,
                created=datetime(2013, 1, 1, tzinfo=UTC),
                mode=CourseMode.VERIFIED,
            )
            with override_waffle_flag(self.waffle_flag, active=True):
                self.login_staff()
                resp = self.client.get(
                    self.get_url(course_key=self.course.id) + '?enrollment_mode={}'.format(CourseMode.AUDIT)
                )

                self._assert_data_all_users(resp)
Example #4
0
    def test_has_staff_access_to_preview_mode(self):
        """
        Test that preview mode is only accessible by staff users.
        """
        course_key = self.course.id
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

        for user in [self.global_staff, self.course_staff, self.course_instructor]:
            self.assertTrue(access.has_staff_access_to_preview_mode(user, course_key))

        self.assertFalse(access.has_staff_access_to_preview_mode(self.student, course_key))

        # we don't want to restrict a staff user, masquerading as student,
        # to access preview mode.

        # Note that self.student now have access to preview mode,
        # `is_masquerading_as_student == True` means user is staff and is
        # masquerading as a student.
        with patch('lms.djangoapps.courseware.access.is_masquerading_as_student') as mock_masquerade:
            mock_masquerade.return_value = True
            for user in [self.global_staff, self.course_staff, self.course_instructor, self.student]:
                self.assertTrue(access.has_staff_access_to_preview_mode(user, course_key))
Example #5
0
 def test_no_id_redirect_otto(self):
     # Create the course modes
     prof_course = CourseFactory.create()
     CourseModeFactory(mode_slug=CourseMode.NO_ID_PROFESSIONAL_MODE,
                       course_id=prof_course.id,
                       min_price=100,
                       sku='TEST',
                       bulk_sku="BULKTEST")
     ecomm_test_utils.update_commerce_config(enabled=True)
     # Enroll the user in the test course
     CourseEnrollmentFactory(is_active=False,
                             mode=CourseMode.NO_ID_PROFESSIONAL_MODE,
                             course_id=prof_course.id,
                             user=self.user)
     # Configure whether we're upgrading or not
     url = reverse('course_modes_choose',
                   args=[six.text_type(prof_course.id)])
     response = self.client.get(url)
     self.assertRedirects(response,
                          'http://testserver/test_basket/add/?sku=TEST',
                          fetch_redirect_response=False)
     ecomm_test_utils.update_commerce_config(enabled=False)
Example #6
0
    def setUp(self):
        super(TestRefundSignal, self).setUp()

        # Ensure the E-Commerce service user exists
        UserFactory(username=settings.ECOMMERCE_SERVICE_WORKER_USERNAME,
                    is_staff=True)

        self.requester = UserFactory(username="******")
        self.student = UserFactory(
            username="******",
            email="*****@*****.**",
        )
        self.course_enrollment = CourseEnrollmentFactory(
            user=self.student,
            course_id=CourseKey.from_string('course-v1:org+course+run'),
            mode=CourseMode.VERIFIED,
        )
        self.course_enrollment.refundable = mock.Mock(return_value=True)

        self.config = CommerceConfiguration.current()
        self.config.enable_automatic_refund_approval = True
        self.config.save()
Example #7
0
    def test_no_id_redirect(self):
        # Create the course modes
        CourseModeFactory.create(mode_slug=CourseMode.NO_ID_PROFESSIONAL_MODE,
                                 course_id=self.course.id,
                                 min_price=100)

        # Enroll the user in the test course
        CourseEnrollmentFactory(is_active=False,
                                mode=CourseMode.NO_ID_PROFESSIONAL_MODE,
                                course_id=self.course.id,
                                user=self.user)

        # Configure whether we're upgrading or not
        url = reverse('course_modes_choose',
                      args=[six.text_type(self.course.id)])
        response = self.client.get(url)
        # Check whether we were correctly redirected
        purchase_workflow = "?purchase_workflow=single"
        start_flow_url = reverse('verify_student_start_flow',
                                 args=[six.text_type(self.course.id)
                                       ]) + purchase_workflow
        self.assertRedirects(response, start_flow_url)
Example #8
0
 def _set_up_course(self, is_course_cohorted, is_user_cohorted,
                    is_moderator):
     cohort_config = {"cohorted": True} if is_course_cohorted else {}
     course = CourseFactory(number=("TestCourse{}".format(len(
         self.courses))),
                            cohort_config=cohort_config)
     self.courses.append(course)
     CourseEnrollmentFactory(user=self.user, course_id=course.id)
     if is_user_cohorted:
         cohort = CourseUserGroup.objects.create(
             name="Test Cohort",
             course_id=course.id,
             group_type=CourseUserGroup.COHORT)
         cohort.users.add(self.user)
         self.cohorts.append(cohort)
     if is_moderator:
         moderator_perm, _ = Permission.objects.get_or_create(
             name="see_all_cohorts")
         moderator_role = Role.objects.create(name="Moderator",
                                              course_id=course.id)
         moderator_role.permissions.add(moderator_perm)
         self.user.roles.add(moderator_role)
Example #9
0
    def test_in_progress_course_upgrade_deadline_check(self, offset, mock_get_programs):
        """
        Verify that if the user's enrollment is not of the same type as the course run,
        the course will only count as in progress if there is another available seat with
        the right type for which the upgrade deadline has not passed.
        """
        course_run_key = generate_course_run_key()
        now = datetime.datetime.now(utc)
        upgrade_deadline = None if not offset else str(now + datetime.timedelta(days=offset))
        required_seat = SeatFactory(type='verified', upgrade_deadline=upgrade_deadline)
        enrolled_seat = SeatFactory(type='audit')
        seats = [required_seat, enrolled_seat]

        data = [
            ProgramFactory(
                courses=[
                    CourseFactory(course_runs=[
                        CourseRunFactory(key=course_run_key, type='verified', seats=seats),
                    ]),
                ]
            )
        ]
        mock_get_programs.return_value = data

        CourseEnrollmentFactory(user=self.user, course_id=course_run_key, mode='audit')

        meter = ProgramProgressMeter(self.user)

        program = data[0]
        expected = [
            ProgressFactory(
                uuid=program['uuid'],
                completed=0,
                in_progress=1 if offset in [None, 1] else 0,
                not_started=1 if offset in [-1] else 0
            )
        ]

        self.assertEqual(meter.progress(count_only=True), expected)
Example #10
0
 def add_cert_to_queue(self, mode):
     """
     Dry method for course enrollment and adding request to
     queue. Returns a mock object containing information about the
     `XQueueInterface.send_to_queue` method, which can be used in other
     assertions.
     """
     CourseEnrollmentFactory(
         user=self.user_2,
         course_id=self.course.id,
         is_active=True,
         mode=mode,
     )
     with patch('courseware.grades.grade',
                Mock(return_value={
                    'grade': 'Pass',
                    'percent': 0.75
                })):
         with patch.object(XQueueInterface, 'send_to_queue') as mock_send:
             mock_send.return_value = (0, None)
             self.xqueue.add_cert(self.user_2, self.course.id)
             return mock_send
    def create_schedule(self, offset=0):
        self.config = ScheduleConfigFactory(create_schedules=True)

        site_patch = patch('openedx.core.djangoapps.schedules.signals.get_current_site', return_value=self.config.site)
        self.addCleanup(site_patch.stop)
        site_patch.start()

        start = datetime.datetime.now(utc) - datetime.timedelta(days=100)
        self.course = CourseFactory.create(start=start, self_paced=True)

        self.enrollment = CourseEnrollmentFactory(
            course_id=self.course.id,
            mode=CourseMode.AUDIT,
        )
        self.enrollment.created = start + datetime.timedelta(days=offset)
        self.enrollment.save()

        self.schedule = self.enrollment.schedule
        self.schedule.start_date = self.enrollment.created
        self.schedule.save()

        self.user = self.enrollment.user
Example #12
0
    def test_compute_social_engagement_score_for_all_courses(self):
        """
        Test to ensure all users enrolled in all open courses have their social scores computed
        """
        course_open = CourseFactory.create()
        course_closed = CourseFactory.create(
            start=datetime(2014, 4, 16, 14, 30),
            end=datetime(2014, 6, 16, 14, 30),
        )
        # Load CourseOverview to cache course metadata
        __ = CourseOverview.get_from_id(course_open.id)
        __ = CourseOverview.get_from_id(course_closed.id)
        __ = CourseOverview.get_from_id(self.course.id)

        user_ids = [user.id for user in self.users]

        for idx in range(1, 10):
            user = UserFactory.create()
            CourseEnrollmentFactory(
                user=user,
                course_id=course_open.id if idx % 2 == 0 else course_closed.id
            )
            if idx % 2 == 0:
                user_ids.append(user.id)

        with patch(
            'social_engagement.management.commands.compute_social_engagement_score.query_yes_no'
        ) as patched_yes_no:
            patched_yes_no.return_value = True

            course1_users = CourseEnrollment.objects.num_enrolled_in(course_open.id)
            course2_users = CourseEnrollment.objects.num_enrolled_in(self.course.id)

            with patch('social_engagement.engagement._get_course_social_stats') as mock_func:
                mock_func.return_value = ((user_id, self.DEFAULT_STATS) for user_id in user_ids)
                call_command('compute_social_engagement_score', compute_for_all_open_courses=True)
        users_count = StudentSocialEngagementScore.objects.all().count()
        open_course_users_count = course1_users + course2_users
        self.assertEqual(users_count, open_course_users_count)
Example #13
0
    def test_congrats_on_enrollment_message(self, create_enrollment):
        # Create the course mode
        CourseModeFactory.create(mode_slug='verified',
                                 course_id=self.course.id)

        if create_enrollment:
            CourseEnrollmentFactory(is_active=True,
                                    course_id=self.course.id,
                                    user=self.user)

        # Check whether congratulations message is shown on the page
        # This should *only* be shown when an enrollment exists
        url = reverse('course_modes_choose',
                      args=[six.text_type(self.course.id)])
        response = self.client.get(url)

        if create_enrollment:
            self.assertContains(response,
                                "Congratulations!  You are now enrolled in")
        else:
            self.assertNotContains(
                response, "Congratulations!  You are now enrolled in")
Example #14
0
    def test_get_student_chats(self):
        """
            Test get_student_chats
        """
        # Without chats return empty array
        response = self.main_client.get(
            reverse('get_student_chats', kwargs={'course_id': self.course.id}))
        self.assertEqual(response.content, '[]')

        # Create a message
        message = EolMessage.objects.create(course_id=self.course.id,
                                            sender_user=self.main_student,
                                            receiver_user=self.staff_user,
                                            text='test_message')

        # With one chat. Message not viewed
        response = self.main_client.get(
            reverse('get_student_chats', kwargs={'course_id': self.course.id}))
        data = json.loads(response.content)
        self.assertEqual(data[0]['receiver_user__username'],
                         self.staff_user.username)
        self.assertEqual(data[0]['min_viewed'], False)
        self.assertEqual(len(data), 1)

        # Add another user to the chat list
        test_student = UserFactory(
            username='******',
            password='******',
            email='*****@*****.**')  # Create the student
        CourseEnrollmentFactory(user=test_student, course_id=self.course.id)
        new_message = EolMessage.objects.create(
            course_id=self.course.id,
            sender_user=test_student,
            receiver_user=self.main_student,
            text='test_message2')
        response = self.main_client.get(
            reverse('get_student_chats', kwargs={'course_id': self.course.id}))
        data = json.loads(response.content)
        self.assertEqual(len(data), 2)
    def test_upgrade_deadline_with_schedule(self):
        """ The property should use either the CourseMode or related Schedule to determine the deadline. """
        course = CourseFactory(self_paced=True)
        CourseModeFactory(
            course_id=course.id,
            mode_slug=CourseMode.VERIFIED,
            # This must be in the future to ensure it is returned by downstream code.
            expiration_datetime=datetime.datetime.now(pytz.UTC) +
            datetime.timedelta(days=30),
        )
        course_overview = CourseOverview.load_from_module_store(course.id)
        enrollment = CourseEnrollmentFactory(
            course_id=course.id,
            mode=CourseMode.AUDIT,
            course=course_overview,
        )

        # The schedule's upgrade deadline should be used if a schedule exists
        DynamicUpgradeDeadlineConfiguration.objects.create(enabled=True)
        schedule = ScheduleFactory(enrollment=enrollment)
        self.assertEqual(enrollment.upgrade_deadline,
                         schedule.upgrade_deadline)
Example #16
0
    def setUp(self):

        # Patching the ENABLE_DISCUSSION_SERVICE value affects the contents of urls.py,
        # so we need to call super.setUp() which reloads urls.py (because
        # of the UrlResetMixin)
        super(ViewsTestCase, self).setUp(create_user=False)

        # create a course
        self.course = CourseFactory.create(
            org='MITx',
            course='999',
            discussion_topics={"Some Topic": {
                "id": "some_topic"
            }},
            display_name='Robot Super Course',
        )
        self.course_id = self.course.id
        # seed the forums permissions and roles
        call_command('seed_permissions_roles',
                     self.course_id.to_deprecated_string())

        # Patch the comment client user save method so it does not try
        # to create a new cc user when creating a django user
        with patch('student.models.cc.User.save'):
            uname = 'student'
            email = '*****@*****.**'
            password = '******'

            # Create the user and make them active so we can log them in.
            self.student = User.objects.create_user(uname, email, password)
            self.student.is_active = True
            self.student.save()

            # Enroll the student in the course
            CourseEnrollmentFactory(user=self.student,
                                    course_id=self.course_id)

            self.client = Client()
            assert_true(self.client.login(username='******', password='******'))
Example #17
0
    def test_email_settings_fulfilled_entitlement(self, mock_email_feature,
                                                  mock_get_course_runs):
        """
        Assert that the Email Settings action is shown when the user has a fulfilled entitlement.
        """
        mock_email_feature.return_value = True
        course_overview = CourseOverviewFactory(start=self.TOMORROW,
                                                self_paced=True,
                                                enrollment_end=self.TOMORROW)
        course_enrollment = CourseEnrollmentFactory(
            user=self.user, course_id=course_overview.id)
        entitlement = CourseEntitlementFactory(
            user=self.user, enrollment_course_run=course_enrollment)
        course_runs = [{
            'key': six.text_type(course_overview.id),
            'uuid': entitlement.course_uuid
        }]
        mock_get_course_runs.return_value = course_runs

        response = self.client.get(self.path)
        self.assertEqual(
            pq(response.content)(self.EMAIL_SETTINGS_ELEMENT_ID).length, 1)
Example #18
0
    def test_update_course_enrollment(self, mock_sailthru_api_post,
                                      mock_sailthru_api_get, mock_sailthru_purchase):
        """test update sailthru user record"""

        # create mocked Sailthru API responses
        mock_sailthru_api_post.return_value = MockSailthruResponse({'ok': True})
        mock_sailthru_api_get.return_value = MockSailthruResponse({'user': {"id": TEST_EMAIL, "fields": {"vars": 1}}})
        mock_sailthru_purchase.return_value = MockSailthruResponse({'ok': True})
        self.user.email = TEST_EMAIL
        CourseEnrollmentFactory(user=self.user, course_id=self.course_id)
        with patch('email_marketing.tasks.build_course_url') as m:
            m.return_value = self.course_url
            update_course_enrollment(TEST_EMAIL, self.course_id, 'audit')
        item = [{
            'vars': {'course_run_id': u'edX/toy/2012_Fall', 'mode': 'audit'},
            'url': self.course_url,
            'price': 0,
            'qty': 1,
            'id': 'edX/toy/2012_Fall-audit',
            'title': 'Course edX/toy/2012_Fall mode: audit'
        }]
        mock_sailthru_purchase.assert_called_with(TEST_EMAIL, item, options={})
Example #19
0
    def test_student_state(self, default_store):
        """
        Verify that saved student state is loaded for xblocks rendered in the index view.
        """
        user = UserFactory()

        with modulestore().default_store(default_store):
            course = CourseFactory.create()
            chapter = ItemFactory.create(parent=course, category='chapter')
            section = ItemFactory.create(parent=chapter, category='view_checker', display_name="Sequence Checker")
            vertical = ItemFactory.create(parent=section, category='view_checker', display_name="Vertical Checker")
            block = ItemFactory.create(parent=vertical, category='view_checker', display_name="Block Checker")

        for item in (section, vertical, block):
            StudentModuleFactory.create(
                student=user,
                course_id=course.id,
                module_state_key=item.scope_ids.usage_id,
                state=json.dumps({'state': unicode(item.scope_ids.usage_id)})
            )

        CourseEnrollmentFactory(user=user, course_id=course.id)

        request = RequestFactory().get(
            reverse(
                'courseware_section',
                kwargs={
                    'course_id': unicode(course.id),
                    'chapter': chapter.url_name,
                    'section': section.url_name,
                }
            )
        )
        request.user = user
        mako_middleware_process_request(request)

        # Trigger the assertions embedded in the ViewCheckerBlocks
        response = views.index(request, unicode(course.id), chapter=chapter.url_name, section=section.url_name)
        self.assertEquals(response.content.count("ViewCheckerPassed"), 3)
Example #20
0
    def test_sharing_icons_for_future_course(self, set_marketing,
                                             set_social_sharing,
                                             modulestore_type):
        """
        Verify that the course sharing icons show up if course is starting in future and
        any of marketing or social sharing urls are set.
        """
        self.course = CourseFactory.create(start=self.TOMORROW,
                                           emit_signals=True,
                                           default_store=modulestore_type)
        self.course_enrollment = CourseEnrollmentFactory(
            course_id=self.course.id, user=self.user)
        self.set_course_sharing_urls(set_marketing, set_social_sharing)

        # Assert course sharing icons
        response = self.client.get(reverse('dashboard'))
        self.assertEqual(
            'Share on Twitter' in response.content.decode('utf-8'),
            set_marketing or set_social_sharing)
        self.assertEqual(
            'Share on Facebook' in response.content.decode('utf-8'),
            set_marketing or set_social_sharing)
    def setUp(self):
        super(ProgressPageCreditRequirementsTest, self).setUp()

        # Create a course and configure it as a credit course
        self.course = CourseFactory.create()
        CreditCourse.objects.create(course_key=self.course.id, enabled=True)  # pylint: disable=no-member

        # Configure credit requirements (passing grade and in-course reverification)
        credit_api.set_credit_requirements(
            self.course.id,  # pylint: disable=no-member
            [{
                "namespace": "grade",
                "name": "grade",
                "display_name": self.MIN_GRADE_REQ_DISPLAY,
                "criteria": {
                    "min_grade": 0.8
                }
            }, {
                "namespace": "reverification",
                "name": "midterm",
                "display_name": self.VERIFICATION_REQ_DISPLAY,
                "criteria": {}
            }])

        # Create a user and log in
        self.user = UserFactory.create(username=self.USERNAME,
                                       password=self.PASSWORD)
        self.user.profile.name = self.USER_FULL_NAME
        self.user.profile.save()

        result = self.client.login(username=self.USERNAME,
                                   password=self.PASSWORD)
        self.assertTrue(result, msg="Could not log in")

        # Enroll the user in the course as "verified"
        self.enrollment = CourseEnrollmentFactory(
            user=self.user,
            course_id=self.course.id,  # pylint: disable=no-member
            mode="verified")
Example #22
0
    def test_pre_requisites_appear_on_dashboard(self):
        """
        When a course has a prerequisite, the dashboard should display the prerequisite.
        If we remove the prerequisite and access the dashboard again, the prerequisite
        should not appear.
        """
        self.pre_requisite_course = CourseFactory.create(org='edx', number='999', display_name='Pre requisite Course')
        self.course = CourseFactory.create(
            org='edx',
            number='998',
            display_name='Test Course',
            pre_requisite_courses=[six.text_type(self.pre_requisite_course.id)]
        )
        self.course_enrollment = CourseEnrollmentFactory(course_id=self.course.id, user=self.user)

        set_prerequisite_courses(self.course.id, [six.text_type(self.pre_requisite_course.id)])
        response = self.client.get(reverse('dashboard'))
        self.assertContains(response, '<div class="prerequisites">')

        remove_prerequisite_course(self.course.id, get_course_milestones(self.course.id)[0])
        response = self.client.get(reverse('dashboard'))
        self.assertNotContains(response, '<div class="prerequisites">')
Example #23
0
    def test_no_certificate_available_date_for_audit_course(self):
        """
        Tests that Certificate Available Date is not visible in the course "Important Course Dates" section
        if the course only has audit mode.
        """
        course = create_course_run()
        audit_user = self.create_user()

        # Enroll learner in the audit mode and verify the course only has 1 mode (audit)
        CourseEnrollmentFactory(course_id=course.id, user=audit_user, mode=CourseMode.AUDIT)
        CourseMode.objects.get(course_id=course.id, mode_slug=CourseMode.VERIFIED).delete()
        all_course_modes = CourseMode.modes_for_course(course.id)
        self.assertEqual(len(all_course_modes), 1)
        self.assertEqual(all_course_modes[0].slug, CourseMode.AUDIT)

        course.certificate_available_date = datetime.now(utc) + timedelta(days=7)
        course.save()

        # Verify Certificate Available Date is not enabled for learner.
        block = CertificateAvailableDate(course, audit_user)
        self.assertFalse(block.is_enabled)
        self.assertNotEqual(block.date, None)
Example #24
0
    def test_courseware_page_unfulfilled_prereqs(self):
        """
        Test courseware access when a course has pre-requisite course yet to be completed
        """
        pre_requisite_course = CourseFactory.create(
            org='edX',
            course='900',
            run='test_run',
        )

        pre_requisite_courses = [unicode(pre_requisite_course.id)]
        course = CourseFactory.create(
            org='edX',
            course='1000',
            run='test_run',
            pre_requisite_courses=pre_requisite_courses,
        )
        set_prerequisite_courses(course.id, pre_requisite_courses)

        test_password = '******'
        user = UserFactory.create()
        user.set_password(test_password)
        user.save()
        self.login(user.email, test_password)
        CourseEnrollmentFactory(user=user, course_id=course.id)

        url = reverse('courseware', args=[unicode(course.id)])
        response = self.client.get(url)
        self.assertRedirects(
            response,
            reverse(
                'dashboard'
            )
        )
        self.assertEqual(response.status_code, 302)

        fulfill_course_milestone(pre_requisite_course.id, user)
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
Example #25
0
    def test_ineligible_cert_whitelisted(self):
        """Test that audit mode students can receive a certificate if they are whitelisted."""
        # Enroll as audit
        CourseEnrollmentFactory(user=self.user_2,
                                course_id=self.course.id,
                                is_active=True,
                                mode='audit')
        # Whitelist student
        CertificateWhitelistFactory(course_id=self.course.id, user=self.user_2)

        # Generate certs
        with mock_passing_grade():
            with patch.object(XQueueInterface, 'send_to_queue') as mock_send:
                mock_send.return_value = (0, None)
                self.xqueue.add_cert(self.user_2, self.course.id)

        # Assert cert generated correctly
        self.assertTrue(mock_send.called)
        certificate = GeneratedCertificate.certificate_for_student(
            self.user_2, self.course.id)
        self.assertIsNotNone(certificate)
        self.assertEqual(certificate.mode, 'audit')
    def test_learner_already_enrolled_in_course(self):
        course_key = self.course_keys[0]
        course = CourseOverview.objects.get(id=course_key)
        CourseEnrollmentFactory(user=self.user, course=course, mode=CourseMode.VERIFIED)

        program_enrollment = self._create_waiting_program_enrollment()
        program_course_enrollments = self._create_waiting_course_enrollments(program_enrollment)

        UserSocialAuth.objects.create(
            user=self.user,
            uid='{0}:{1}'.format(self.provider_slug, self.external_id)
        )

        self._assert_program_enrollment_user(program_enrollment, self.user)

        duplicate_program_course_enrollment = program_course_enrollments[0]
        self._assert_program_course_enrollment(
            duplicate_program_course_enrollment, CourseMode.VERIFIED
        )

        program_course_enrollment = program_course_enrollments[1]
        self._assert_program_course_enrollment(program_course_enrollment)
Example #27
0
    def test_access_on_course_with_pre_requisites(self):
        """
        Test course access when a course has pre-requisite course yet to be completed
        """
        seed_milestone_relationship_types()
        user = UserFactory.create()

        pre_requisite_course = CourseFactory.create(org='test_org',
                                                    number='788',
                                                    run='test_run')

        pre_requisite_courses = [unicode(pre_requisite_course.id)]
        course = CourseFactory.create(
            org='test_org',
            number='786',
            run='test_run',
            pre_requisite_courses=pre_requisite_courses)
        set_prerequisite_courses(course.id, pre_requisite_courses)

        # user should not be able to load course even if enrolled
        CourseEnrollmentFactory(user=user, course_id=course.id)
        response = access._has_access_course(
            user, 'view_courseware_with_prerequisites', course)
        self.assertFalse(response)
        self.assertIsInstance(response, access_response.MilestoneError)
        # Staff can always access course
        staff = StaffFactory.create(course_key=course.id)
        self.assertTrue(
            access._has_access_course(staff,
                                      'view_courseware_with_prerequisites',
                                      course))

        # User should be able access after completing required course
        fulfill_course_milestone(pre_requisite_course.id, user)
        self.assertTrue(
            access._has_access_course(user,
                                      'view_courseware_with_prerequisites',
                                      course))
Example #28
0
    def test_student_has_access(self):
        """
        Tests course student have right access to content w/o preview.
        """
        course_key = self.course.id
        chapter = ItemFactory.create(category="chapter",
                                     parent_location=self.course.location)
        overview = CourseOverview.get_from_id(course_key)

        # Enroll student to the course
        CourseEnrollmentFactory(user=self.student, course_id=self.course.id)

        modules = [
            self.course,
            overview,
            chapter,
        ]
        with patch('lms.djangoapps.courseware.access.in_preview_mode'
                   ) as mock_preview:
            mock_preview.return_value = False
            for obj in modules:
                self.assertTrue(
                    bool(
                        access.has_access(self.student,
                                          'load',
                                          obj,
                                          course_key=self.course.id)))

        with patch('lms.djangoapps.courseware.access.in_preview_mode'
                   ) as mock_preview:
            mock_preview.return_value = True
            for obj in modules:
                self.assertFalse(
                    bool(
                        access.has_access(self.student,
                                          'load',
                                          obj,
                                          course_key=self.course.id)))
Example #29
0
    def test_links_to_detail_pages(self):
        """
        Verify that links to detail pages are present when enabled, instead of
        links to the marketing site.
        """
        self.create_programs_config()
        self.mock_programs_api(self.data)

        CourseEnrollmentFactory(user=self.user, course_id=self.course.id)  # pylint: disable=no-member

        response = self.client.get(self.url)
        actual = self.load_serialized_data(response, 'programsData')
        actual = sorted(actual, key=self.program_sort_key)

        for index, actual_program in enumerate(actual):
            expected_program = self.data[index]

            base = reverse('program_details_view', args=[expected_program['id']]).rstrip('/')
            slug = slugify(expected_program['name'])
            self.assertEqual(
                actual_program['detail_url'],
                '{}/{}'.format(base, slug)
            )

        # Verify that links to the marketing site are present when detail pages are disabled.
        self.create_programs_config(program_details_enabled=False)

        response = self.client.get(self.url)
        actual = self.load_serialized_data(response, 'programsData')
        actual = sorted(actual, key=self.program_sort_key)

        for index, actual_program in enumerate(actual):
            expected_program = self.data[index]

            self.assertEqual(
                actual_program['detail_url'],
                '{}/{}'.format(self.marketing_root, expected_program['marketing_slug'])
            )
Example #30
0
    def test_suggested_prices(self, price_list):

        # Create the course modes
        for mode in ('audit', 'honor'):
            CourseModeFactory.create(mode_slug=mode, course_id=self.course.id)

        CourseModeFactory.create(mode_slug='verified',
                                 course_id=self.course.id,
                                 suggested_prices=price_list)

        # Enroll the user in the test course to emulate
        # automatic enrollment
        CourseEnrollmentFactory(is_active=True,
                                course_id=self.course.id,
                                user=self.user)

        # Verify that the prices render correctly
        response = self.client.get(
            reverse('course_modes_choose', args=[unicode(self.course.id)]),
            follow=False,
        )

        self.assertEquals(response.status_code, 200)