Exemplo n.º 1
0
    def assertChangeEmailSent(self, email_user):
        """Assert that the correct email was sent to confirm an email change"""
        context = {
            'old_email': self.user.email,
            'new_email': self.pending_change_request.new_email,
        }
        self.assertEmailUser(
            email_user,
            'emails/email_change_subject.txt',
            context,
            'emails/confirm_email_change.txt',
            context
        )

        # Thorough tests for safe_get_host are elsewhere; here we just want a quick URL sanity check
        request = RequestFactory().post('unused_url')
        request.user = self.user
        request.META['HTTP_HOST'] = "aGenericValidHostName"
        self.append_allowed_hosts("aGenericValidHostName")

        mako_middleware_process_request(request)
        body = render_to_string('emails/confirm_email_change.txt', context)
        url = safe_get_host(request)

        self.assertIn(url, body)
Exemplo n.º 2
0
    def call_view(self,
                  mock_request,
                  commentable_id,
                  user,
                  group_id,
                  pass_group_id=True,
                  is_ajax=False):
        kwargs = {}
        if group_id:
            kwargs['group_id'] = group_id
        mock_request.side_effect = make_mock_request_impl(
            "dummy content", **kwargs)

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
        request = RequestFactory().get("dummy_url",
                                       data=request_data,
                                       **headers)
        request.user = user
        mako_middleware_process_request(request)
        return views.user_profile(request,
                                  self.course.id.to_deprecated_string(),
                                  user.id)
Exemplo n.º 3
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)
Exemplo n.º 4
0
    def call_view_for_profiled_user(
            self, mock_request, requesting_user, profiled_user, group_id, pass_group_id, is_ajax=False
    ):
        """
        Calls "user_profile" view method on behalf of "requesting_user" to get information about
        the user "profiled_user".
        """
        kwargs = {}
        if group_id:
            kwargs['group_id'] = group_id
        mock_request.side_effect = make_mock_request_impl("dummy content", **kwargs)

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
        request = RequestFactory().get(
            "dummy_url",
            data=request_data,
            **headers
        )
        request.user = requesting_user
        mako_middleware_process_request(request)
        return views.user_profile(
            request,
            self.course.id.to_deprecated_string(),
            profiled_user.id
        )
    def base_extauth_bypass_sending_activation_email(
            self, bypass_activation_email_for_extauth_setting):
        """
        Tests user creation without sending activation email when
        doing external auth
        """

        request = self.request_factory.post(self.url, self.params)
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(
            settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(
            external_id='*****@*****.**',
            external_email='*****@*****.**',
            internal_password=self.params['password'],
            external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        mako_middleware_process_request(request)
        with mock.patch('django.contrib.auth.models.User.email_user'
                        ) as mock_send_mail:
            student.views.create_account(request)

        # check that send_mail is called
        if bypass_activation_email_for_extauth_setting:
            self.assertFalse(mock_send_mail.called)
        else:
            self.assertTrue(mock_send_mail.called)
Exemplo n.º 6
0
    def assertReactivateEmailSent(self, email_user):
        """Assert that the correct reactivation email has been sent"""
        context = {
            'name': self.user.profile.name,
            'key': self.registration.activation_key
        }

        self.assertEmailUser(
            email_user,
            'emails/activation_email_subject.txt',
            context,
            'emails/activation_email.txt',
            context
        )

        # Thorough tests for safe_get_host are elsewhere; here we just want a quick URL sanity check
        request = RequestFactory().post('unused_url')
        request.user = self.user
        request.META['HTTP_HOST'] = "aGenericValidHostName"
        self.append_allowed_hosts("aGenericValidHostName")

        mako_middleware_process_request(request)
        body = render_to_string('emails/activation_email.txt', context)
        host = safe_get_host(request)

        self.assertIn(host, body)
Exemplo n.º 7
0
    def test_already_associated_exception_populates_dashboard_with_error(self):
        # Instrument the pipeline with an exception. We test that the
        # exception is raised correctly separately, so it's ok that we're
        # raising it artificially here. This makes the linked=True artificial
        # in the final assert because in practice the account would be
        # unlinked, but getting that behavior is cumbersome here and already
        # covered in other tests. Using linked=True does, however, let us test
        # that the duplicate error has no effect on the state of the controls.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username())
        self.assert_social_auth_exists_for_user(user, strategy)

        self.client.get('/login')
        self.client.get(pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN))
        actions.do_complete(strategy, social_views._do_login)  # pylint: disable-msg=protected-access

        mako_middleware_process_request(strategy.request)
        student_views.signin_user(strategy.request)
        student_views.login_user(strategy.request)
        actions.do_complete(strategy, social_views._do_login, user=user)  # pylint: disable-msg=protected-access

        # Monkey-patch storage for messaging; pylint: disable-msg=protected-access
        request._messages = fallback.FallbackStorage(request)
        middleware.ExceptionMiddleware().process_exception(
            request,
            exceptions.AuthAlreadyAssociated(self.PROVIDER_CLASS.BACKEND_CLASS.name, 'account is already in use.'))

        self.assert_dashboard_response_looks_correct(
            student_views.dashboard(request), user, duplicate=True, linked=True)
Exemplo n.º 8
0
    def test_activate_block_id(self):
        user = UserFactory()

        course = CourseFactory.create()
        chapter = ItemFactory.create(parent=course, category='chapter')
        section = ItemFactory.create(parent=chapter, category='sequential', display_name="Sequence")
        vertical = ItemFactory.create(parent=section, category='vertical', display_name="Vertical")
        ItemFactory.create(parent=vertical, category='id_checker', display_name="ID Checker")

        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,
                }
            ) + '?activate_block_id=test_block_id'
        )
        request.user = user
        mako_middleware_process_request(request)

        response = views.index(request, unicode(course.id), chapter=chapter.url_name, section=section.url_name)
        self.assertIn("Activate Block ID: test_block_id", response.content)
Exemplo n.º 9
0
    def get_text(self, course):
        """ Returns the HTML for the progress page """

        mako_middleware_process_request(self.request)
        return views.progress(self.request,
                              course_id=course.id.to_deprecated_string(),
                              student_id=self.user.id).content
Exemplo n.º 10
0
    def get_response(self, mock_request, params, **headers):
        mock_request.side_effect = make_mock_request_impl(
            self.TEST_THREAD_TEXT, self.TEST_THREAD_ID)
        request = RequestFactory().get("dummy_url", data=params, **headers)
        request.user = self.student

        mako_middleware_process_request(request)
        response = views.user_profile(request,
                                      self.course.id.to_deprecated_string(),
                                      self.profiled_user.id)
        mock_request.assert_any_call("get",
                                     StringEndsWithMatcher(
                                         '/users/{}/active_threads'.format(
                                             self.profiled_user.id)),
                                     data=None,
                                     params=PartialDictMatcher({
                                         "course_id":
                                         self.course.id.to_deprecated_string(),
                                         "page":
                                         params.get("page", 1),
                                         "per_page":
                                         views.THREADS_PER_PAGE
                                     }),
                                     headers=ANY,
                                     timeout=ANY)
        return response
Exemplo n.º 11
0
    def test_full_pipeline_succeeds_for_linking_account(self):
        # First, create, the request and strategy that store pipeline state,
        # configure the backend, and mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN,
            redirect_uri='social:complete')
        request.backend.auth_complete = mock.MagicMock(
            return_value=self.fake_auth_complete(strategy))
        pipeline.analytics.track = mock.MagicMock()
        request.user = self.create_user_models_for_existing_account(
            strategy,
            '*****@*****.**',
            'password',
            self.get_username(),
            skip_social_auth=True)

        # Instrument the pipeline to get to the dashboard with the full
        # expected state.
        self.client.get(
            pipeline.get_login_url(self.provider.provider_id,
                                   pipeline.AUTH_ENTRY_LOGIN))
        actions.do_complete(request.backend, social_views._do_login)  # pylint: disable=protected-access

        mako_middleware_process_request(strategy.request)
        student_views.signin_user(strategy.request)
        student_views.login_user(strategy.request)
        actions.do_complete(request.backend, social_views._do_login)  # pylint: disable=protected-access

        # First we expect that we're in the unlinked state, and that there
        # really is no association in the backend.
        self.assert_account_settings_context_looks_correct(
            account_settings_context(request), request.user, linked=False)
        self.assert_social_auth_does_not_exist_for_user(request.user, strategy)

        # We should be redirected back to the complete page, setting
        # the "logged in" cookie for the marketing site.
        self.assert_logged_in_cookie_redirect(
            actions.do_complete(
                request.backend,
                social_views._do_login,
                request.user,
                None,  # pylint: disable=protected-access
                redirect_field_name=auth.REDIRECT_FIELD_NAME))

        # Set the cookie and try again
        self.set_logged_in_cookies(request)

        # Fire off the auth pipeline to link.
        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(
                request.backend,
                social_views._do_login,
                request.user,
                None,  # pylint: disable=protected-access
                redirect_field_name=auth.REDIRECT_FIELD_NAME))

        # Now we expect to be in the linked state, with a backend entry.
        self.assert_social_auth_exists_for_user(request.user, strategy)
        self.assert_account_settings_context_looks_correct(
            account_settings_context(request), request.user, linked=True)
Exemplo n.º 12
0
    def test_access_student_progress_ccx(self):
        """
        Assert that only a coach can see progress of student.
        """
        ccx_locator = self.make_ccx()
        student = UserFactory()

        # Enroll user
        CourseEnrollment.enroll(student, ccx_locator)

        # Test for access of a coach
        request = self.request_factory.get(reverse('about_course', args=[unicode(ccx_locator)]))
        request.user = self.coach
        mako_middleware_process_request(request)
        resp = views.progress(request, course_id=unicode(ccx_locator), student_id=student.id)
        self.assertEqual(resp.status_code, 200)

        # Assert access of a student
        request = self.request_factory.get(reverse('about_course', args=[unicode(ccx_locator)]))
        request.user = student
        mako_middleware_process_request(request)

        with self.assertRaises(Http404) as context:
            views.progress(request, course_id=unicode(ccx_locator), student_id=self.coach.id)

        self.assertIsNotNone(context.exception)
Exemplo n.º 13
0
    def test_registration_form_submit(self, identity):
        """
        Tests user creation after the registration form that pops is submitted.  If there is no shib
        ExternalAuthMap in the session, then the created user should take the username and email from the
        request.

        Uses django test client for its session support
        """
        # First we pop the registration form
        client = DjangoTestClient()
        response1 = client.get(path='/shib-login/', data={}, follow=False, **identity)
        # Then we have the user answer the registration form
        # These are unicode because request.POST returns unicode
        postvars = {'email': u'*****@*****.**',
                    'username': u'post_username',  # django usernames can't be unicode
                    'password': u'post_pássword',
                    'name': u'post_náme',
                    'terms_of_service': u'true',
                    'honor_code': u'true'}
        # use RequestFactory instead of TestClient here because we want access to request.user
        request2 = self.request_factory.post('/create_account', data=postvars)
        request2.session = client.session
        request2.user = AnonymousUser()

        mako_middleware_process_request(request2)
        with patch('student.views.AUDIT_LOG') as mock_audit_log:
            _response2 = create_account(request2)

        user = request2.user
        mail = identity.get('mail')
Exemplo n.º 14
0
    def test_full_pipeline_succeeds_for_unlinking_account(self):
        # First, create, the request and strategy that store pipeline state,
        # configure the backend, and mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username())
        self.assert_social_auth_exists_for_user(user, strategy)

        # We're already logged in, so simulate that the cookie is set correctly
        self.set_logged_in_cookie(request)

        # Instrument the pipeline to get to the dashboard with the full
        # expected state.
        self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN))
        actions.do_complete(strategy, social_views._do_login)  # pylint: disable-msg=protected-access

        mako_middleware_process_request(strategy.request)
        student_views.signin_user(strategy.request)
        student_views.login_user(strategy.request)
        actions.do_complete(strategy, social_views._do_login, user=user)  # pylint: disable-msg=protected-access

        # First we expect that we're in the linked state, with a backend entry.
        self.assert_account_settings_context_looks_correct(account_settings_context(request), user, linked=True)
        self.assert_social_auth_exists_for_user(request.user, strategy)

        # Fire off the disconnect pipeline to unlink.
        self.assert_redirect_to_dashboard_looks_correct(actions.do_disconnect(
            request.social_strategy, request.user, None, redirect_field_name=auth.REDIRECT_FIELD_NAME))

        # Now we expect to be in the unlinked state, with no backend entry.
        self.assert_account_settings_context_looks_correct(account_settings_context(request), user, linked=False)
        self.assert_social_auth_does_not_exist_for_user(user, strategy)
Exemplo n.º 15
0
    def base_extauth_bypass_sending_activation_email(self, bypass_activation_email_for_extauth_setting):
        """
        Tests user creation without sending activation email when
        doing external auth
        """

        request = self.request_factory.post(self.url, self.params)
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(external_id='*****@*****.**',
                                  external_email='*****@*****.**',
                                  internal_password=self.params['password'],
                                  external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        mako_middleware_process_request(request)
        with mock.patch('django.contrib.auth.models.User.email_user') as mock_send_mail:
            student.views.create_account(request)

        # check that send_mail is called
        if bypass_activation_email_for_extauth_setting:
            self.assertFalse(mock_send_mail.called)
        else:
            self.assertTrue(mock_send_mail.called)
Exemplo n.º 16
0
    def call_view_for_profiled_user(
            self, mock_request, requesting_user, profiled_user, group_id, pass_group_id, is_ajax=False
    ):
        """
        Calls "user_profile" view method on behalf of "requesting_user" to get information about
        the user "profiled_user".
        """
        kwargs = {}
        if group_id:
            kwargs['group_id'] = group_id
        mock_request.side_effect = make_mock_request_impl("dummy content", **kwargs)

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
        request = RequestFactory().get(
            "dummy_url",
            data=request_data,
            **headers
        )
        request.user = requesting_user
        mako_middleware_process_request(request)
        return views.user_profile(
            request,
            self.course.id.to_deprecated_string(),
            profiled_user.id
        )
Exemplo n.º 17
0
    def assertChangeEmailSent(self, email_user):
        """Assert that the correct email was sent to confirm an email change"""
        context = {
            'old_email': self.user.email,
            'new_email': self.pending_change_request.new_email,
        }
        self.assertEmailUser(
            email_user,
            'emails/email_change_subject.txt',
            context,
            'emails/confirm_email_change.txt',
            context
        )

        # Thorough tests for safe_get_host are elsewhere; here we just want a quick URL sanity check
        request = RequestFactory().post('unused_url')
        request.user = self.user
        request.META['HTTP_HOST'] = "aGenericValidHostName"
        self.append_allowed_hosts("aGenericValidHostName")

        mako_middleware_process_request(request)
        body = render_to_string('emails/confirm_email_change.txt', context)
        url = safe_get_host(request)

        self.assertIn(url, body)
Exemplo n.º 18
0
    def assertReactivateEmailSent(self, email_user):
        """Assert that the correct reactivation email has been sent"""
        context = {
            'name': self.user.profile.name,
            'key': self.registration.activation_key
        }

        self.assertEmailUser(
            email_user,
            'emails/activation_email_subject.txt',
            context,
            'emails/activation_email.txt',
            context
        )

        # Thorough tests for safe_get_host are elsewhere; here we just want a quick URL sanity check
        request = RequestFactory().post('unused_url')
        request.user = self.user
        request.META['HTTP_HOST'] = "aGenericValidHostName"
        self.append_allowed_hosts("aGenericValidHostName")

        mako_middleware_process_request(request)
        body = render_to_string('emails/activation_email.txt', context)
        host = safe_get_host(request)

        self.assertIn(host, body)
Exemplo n.º 19
0
    def test_full_pipeline_succeeds_for_unlinking_account(self):
        # First, create, the request and strategy that store pipeline state,
        # configure the backend, and mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username())
        self.assert_social_auth_exists_for_user(user, strategy)

        # We're already logged in, so simulate that the cookie is set correctly
        self.set_logged_in_cookie(request)

        # Instrument the pipeline to get to the dashboard with the full
        # expected state.
        self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN))
        actions.do_complete(strategy, social_views._do_login)  # pylint: disable-msg=protected-access

        mako_middleware_process_request(strategy.request)
        student_views.signin_user(strategy.request)
        student_views.login_user(strategy.request)
        actions.do_complete(strategy, social_views._do_login, user=user)  # pylint: disable-msg=protected-access

        # First we expect that we're in the linked state, with a backend entry.
        self.assert_dashboard_response_looks_correct(student_views.dashboard(request), user, linked=True)
        self.assert_social_auth_exists_for_user(request.user, strategy)

        # Fire off the disconnect pipeline to unlink.
        self.assert_redirect_to_dashboard_looks_correct(actions.do_disconnect(
            request.social_strategy, request.user, None, redirect_field_name=auth.REDIRECT_FIELD_NAME))

        # Now we expect to be in the unlinked state, with no backend entry.
        self.assert_dashboard_response_looks_correct(student_views.dashboard(request), user, linked=False)
        self.assert_social_auth_does_not_exist_for_user(user, strategy)
Exemplo n.º 20
0
    def test_already_associated_exception_populates_dashboard_with_error(self):
        # Instrument the pipeline with an exception. We test that the
        # exception is raised correctly separately, so it's ok that we're
        # raising it artificially here. This makes the linked=True artificial
        # in the final assert because in practice the account would be
        # unlinked, but getting that behavior is cumbersome here and already
        # covered in other tests. Using linked=True does, however, let us test
        # that the duplicate error has no effect on the state of the controls.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username())
        self.assert_social_auth_exists_for_user(user, strategy)

        self.client.get('/login')
        self.client.get(pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN))
        actions.do_complete(strategy, social_views._do_login)  # pylint: disable-msg=protected-access

        mako_middleware_process_request(strategy.request)
        student_views.signin_user(strategy.request)
        student_views.login_user(strategy.request)
        actions.do_complete(strategy, social_views._do_login, user=user)  # pylint: disable-msg=protected-access

        # Monkey-patch storage for messaging; pylint: disable-msg=protected-access
        request._messages = fallback.FallbackStorage(request)
        middleware.ExceptionMiddleware().process_exception(
            request,
            exceptions.AuthAlreadyAssociated(self.PROVIDER_CLASS.BACKEND_CLASS.name, 'account is already in use.'))

        self.assert_account_settings_context_looks_correct(
            account_settings_context(request), user, duplicate=True, linked=True)
Exemplo n.º 21
0
    def test_full_pipeline_succeeds_registering_new_account(self):
        # First, create, the request and strategy that store pipeline state.
        # Mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))

        # Begin! Grab the registration page and check the login control on it.
        self.assert_register_response_before_pipeline_looks_correct(self.client.get('/register'))

        # The pipeline starts by a user GETting /auth/login/<provider>.
        # Synthesize that request and check that it redirects to the correct
        # provider page.
        self.assert_redirect_to_provider_looks_correct(self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN)))

        # Next, the provider makes a request against /auth/complete/<provider>.
        # pylint:disable-msg=protected-access
        self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))

        mako_middleware_process_request(strategy.request)
        # At this point we know the pipeline has resumed correctly. Next we
        # fire off the view that displays the registration form.
        self.assert_register_response_in_pipeline_looks_correct(
            student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])

        # Next, we invoke the view that handles the POST. Not all providers
        # supply email. Manually add it as the user would have to; this
        # also serves as a test of overriding provider values. Always provide a
        # password for us to check that we override it properly.
        overridden_password = strategy.request.POST.get('password')
        email = '*****@*****.**'

        if not strategy.request.POST.get('email'):
            strategy.request.POST = self.get_registration_post_vars({'email': email})

        # The user must not exist yet...
        with self.assertRaises(auth_models.User.DoesNotExist):
            self.get_user_by_email(strategy, email)

        # ...but when we invoke create_account the existing edX view will make
        # it, but not social auths. The pipeline creates those later.
        self.assert_json_success_response_looks_correct(student_views.create_account(strategy.request))
        # We've overridden the user's password, so authenticate() with the old
        # value won't work:
        created_user = self.get_user_by_email(strategy, email)
        self.assert_password_overridden_by_pipeline(overridden_password, created_user.username)

        # At this point the user object exists, but there is no associated
        # social auth.
        self.assert_social_auth_does_not_exist_for_user(created_user, strategy)

        # Pick the pipeline back up. This will create the account association
        # and send the user to the dashboard, where the association will be
        # displayed.
        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(strategy, social_views._do_login, user=created_user))
        self.assert_social_auth_exists_for_user(created_user, strategy)
        self.assert_dashboard_response_looks_correct(student_views.dashboard(request), created_user, linked=True)
Exemplo n.º 22
0
        def test_user(user):
            request = self.request_factory.get("dummy")
            request.user = AnonymousUser()

            mako_middleware_process_request(request)
            response = set_subscription(request, self.tokens[user], subscribe=False)
            self.assertEqual(response.status_code, 200)
            self.assertNotPrefExists(user)
Exemplo n.º 23
0
        def test_user(user):
            request = self.request_factory.get("dummy")
            request.user = AnonymousUser()

            mako_middleware_process_request(request)
            response = set_subscription(request, self.tokens[user], subscribe=False)
            self.assertEqual(response.status_code, 200)
            self.assertNotPrefExists(user)
Exemplo n.º 24
0
    def setUp(self):
        super(ProgressPageTests, self).setUp()
        self.request_factory = RequestFactory()
        self.user = UserFactory.create()
        self.request = self.request_factory.get("foo")
        self.request.user = self.user

        mako_middleware_process_request(self.request)

        self.setup_course()
Exemplo n.º 25
0
    def setUp(self):
        super(ProgressPageTests, self).setUp()
        self.request_factory = RequestFactory()
        self.user = UserFactory.create()
        self.request = self.request_factory.get("foo")
        self.request.user = self.user

        mako_middleware_process_request(self.request)

        self.setup_course()
Exemplo n.º 26
0
    def test_user_requested_access(self):
        add_user_with_status_unrequested(self.user)
        self.assertEqual('unrequested', get_course_creator_status(self.user))

        request = RequestFactory().get('/')
        request.user = self.user

        mako_middleware_process_request(request)
        user_requested_access(self.user)
        self.assertEqual('pending', get_course_creator_status(self.user))
Exemplo n.º 27
0
        def test_user(user):
            # start without a pref key
            self.assertFalse(UserPreference.objects.filter(user=user, key=NOTIFICATION_PREF_KEY))
            request = self.request_factory.get("dummy")
            request.user = AnonymousUser()

            mako_middleware_process_request(request)
            response = set_subscription(request, self.tokens[user], subscribe=True)
            self.assertEqual(response.status_code, 200)
            self.assertPrefValid(user)
Exemplo n.º 28
0
    def test_user_requested_access(self):
        add_user_with_status_unrequested(self.user)
        self.assertEqual('unrequested', get_course_creator_status(self.user))

        request = RequestFactory().get('/')
        request.user = self.user

        mako_middleware_process_request(request)
        user_requested_access(self.user)
        self.assertEqual('pending', get_course_creator_status(self.user))
Exemplo n.º 29
0
        def test_user(user):
            # start without a pref key
            self.assertFalse(UserPreference.objects.filter(user=user, key=NOTIFICATION_PREF_KEY))
            request = self.request_factory.get("dummy")
            request.user = AnonymousUser()

            mako_middleware_process_request(request)
            response = set_subscription(request, self.tokens[user], subscribe=True)
            self.assertEqual(response.status_code, 200)
            self.assertPrefValid(user)
Exemplo n.º 30
0
    def test_none_user_index_access_with_startdate_fails(self):
        """
        This is a regression test for a bug where the incoming user is
        anonymous and start dates are being checked.  It replaces a previous
        test as it solves the issue in a different way
        """
        request = self.factory.get('/')
        request.user = AnonymousUser()

        mako_middleware_process_request(request)
        student.views.index(request)
Exemplo n.º 31
0
    def test_signin_fails_if_account_not_active(self):
        _, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        user = self.create_user_models_for_existing_account(strategy, '*****@*****.**', 'password', self.get_username())

        user.is_active = False
        user.save()

        mako_middleware_process_request(strategy.request)
        self.assert_json_failure_response_is_inactive_account(student_views.login_user(strategy.request))
Exemplo n.º 32
0
    def test_signin_fails_if_account_not_active(self):
        _, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        user = self.create_user_models_for_existing_account(strategy, '*****@*****.**', 'password', self.get_username())

        user.is_active = False
        user.save()

        mako_middleware_process_request(strategy.request)
        self.assert_json_failure_response_is_inactive_account(student_views.login_user(strategy.request))
Exemplo n.º 33
0
    def test_problem_list(self):
        """
        Ensure that the problem list from the grading controller server can be rendered properly locally
        @return:
        """
        request = RequestFactory().get(
            reverse("open_ended_problems", kwargs={'course_id': self.course_key})
        )
        request.user = self.user

        mako_middleware_process_request(request)
        response = views.student_problem_list(request, self.course.id.to_deprecated_string())
        self.assertRegexpMatches(response.content, "Here is a list of open ended problems for this course.")
Exemplo n.º 34
0
    def test_problem_list(self):
        """
        Ensure that the problem list from the grading controller server can be rendered properly locally
        @return:
        """
        request = RequestFactory().get(
            reverse("open_ended_problems", kwargs={'course_id': self.course_key})
        )
        request.user = self.user

        mako_middleware_process_request(request)
        response = views.student_problem_list(request, self.course.id.to_deprecated_string())
        self.assertRegexpMatches(response.content, "Here is a list of open ended problems for this course.")
Exemplo n.º 35
0
    def test_full_pipeline_succeeds_for_signing_in_to_existing_active_account(self):
        # First, create, the request and strategy that store pipeline state,
        # configure the backend, and mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        pipeline.analytics.track = mock.MagicMock()
        user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username())
        self.assert_social_auth_exists_for_user(user, strategy)
        self.assertTrue(user.is_active)

        # Begin! Ensure that the login form contains expected controls before
        # the user starts the pipeline.
        self.assert_login_response_before_pipeline_looks_correct(self.client.get('/login'))

        # The pipeline starts by a user GETting /auth/login/<provider>.
        # Synthesize that request and check that it redirects to the correct
        # provider page.
        self.assert_redirect_to_provider_looks_correct(self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN)))

        # Next, the provider makes a request against /auth/complete/<provider>
        # to resume the pipeline.
        # pylint: disable-msg=protected-access
        self.assert_redirect_to_login_looks_correct(actions.do_complete(strategy, social_views._do_login))

        mako_middleware_process_request(strategy.request)
        # At this point we know the pipeline has resumed correctly. Next we
        # fire off the view that displays the login form and posts it via JS.
        self.assert_login_response_in_pipeline_looks_correct(student_views.signin_user(strategy.request))

        # Next, we invoke the view that handles the POST, and expect it
        # redirects to /auth/complete. In the browser ajax handlers will
        # redirect the user to the dashboard; we invoke it manually here.
        self.assert_json_success_response_looks_correct(student_views.login_user(strategy.request))

        # We should be redirected back to the complete page, setting
        # the "logged in" cookie for the marketing site.
        self.assert_logged_in_cookie_redirect(actions.do_complete(
            request.social_strategy, social_views._do_login, request.user, None,  # pylint: disable-msg=protected-access
            redirect_field_name=auth.REDIRECT_FIELD_NAME
        ))

        # Set the cookie and try again
        self.set_logged_in_cookie(request)

        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(strategy, social_views._do_login, user=user))
        self.assert_account_settings_context_looks_correct(account_settings_context(request), user)
Exemplo n.º 36
0
    def test_full_pipeline_succeeds_for_signing_in_to_existing_active_account(self):
        # First, create, the request and strategy that store pipeline state,
        # configure the backend, and mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        pipeline.analytics.track = mock.MagicMock()
        user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username())
        self.assert_social_auth_exists_for_user(user, strategy)
        self.assertTrue(user.is_active)

        # Begin! Ensure that the login form contains expected controls before
        # the user starts the pipeline.
        self.assert_login_response_before_pipeline_looks_correct(self.client.get('/login'))

        # The pipeline starts by a user GETting /auth/login/<provider>.
        # Synthesize that request and check that it redirects to the correct
        # provider page.
        self.assert_redirect_to_provider_looks_correct(self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN)))

        # Next, the provider makes a request against /auth/complete/<provider>
        # to resume the pipeline.
        # pylint: disable-msg=protected-access
        self.assert_redirect_to_login_looks_correct(actions.do_complete(strategy, social_views._do_login))

        mako_middleware_process_request(strategy.request)
        # At this point we know the pipeline has resumed correctly. Next we
        # fire off the view that displays the login form and posts it via JS.
        self.assert_login_response_in_pipeline_looks_correct(student_views.signin_user(strategy.request))

        # Next, we invoke the view that handles the POST, and expect it
        # redirects to /auth/complete. In the browser ajax handlers will
        # redirect the user to the dashboard; we invoke it manually here.
        self.assert_json_success_response_looks_correct(student_views.login_user(strategy.request))

        # We should be redirected back to the complete page, setting
        # the "logged in" cookie for the marketing site.
        self.assert_logged_in_cookie_redirect(actions.do_complete(
            request.social_strategy, social_views._do_login, request.user, None,  # pylint: disable-msg=protected-access
            redirect_field_name=auth.REDIRECT_FIELD_NAME
        ))

        # Set the cookie and try again
        self.set_logged_in_cookie(request)

        self.assert_redirect_to_dashboard_looks_correct(
            actions.do_complete(strategy, social_views._do_login, user=user))
        self.assert_dashboard_response_looks_correct(student_views.dashboard(request), user)
Exemplo n.º 37
0
    def test_new_account_registration_fails_if_email_exists(self):
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        # pylint: disable-msg=protected-access
        self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))

        mako_middleware_process_request(strategy.request)
        self.assert_register_response_in_pipeline_looks_correct(
            student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])
        strategy.request.POST = self.get_registration_post_vars()
        # Create twice: once successfully, and once causing a collision.
        student_views.create_account(strategy.request)
        self.assert_json_failure_response_is_username_collision(student_views.create_account(strategy.request))
Exemplo n.º 38
0
    def test_new_account_registration_fails_if_email_exists(self):
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_REGISTER, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        # pylint: disable-msg=protected-access
        self.assert_redirect_to_register_looks_correct(actions.do_complete(strategy, social_views._do_login))

        mako_middleware_process_request(strategy.request)
        self.assert_register_response_in_pipeline_looks_correct(
            student_views.register_user(strategy.request), pipeline.get(request)['kwargs'])
        strategy.request.POST = self.get_registration_post_vars()
        # Create twice: once successfully, and once causing a collision.
        student_views.create_account(strategy.request)
        self.assert_json_failure_response_is_username_collision(student_views.create_account(strategy.request))
Exemplo n.º 39
0
    def _test_action(self, action):
        """
        Test for XSS vulnerability in the given action

        Build a request with the given action, call the instructor dashboard
        view, and check that HTML code in a user's name is properly escaped.
        """
        req = self._request_factory.post("dummy_url", data={"action": action})
        req.user = self._instructor
        req.session = {}

        mako_middleware_process_request(req)
        resp = legacy.instructor_dashboard(req, self._course.id.to_deprecated_string())
        respUnicode = resp.content.decode(settings.DEFAULT_CHARSET)
        self.assertNotIn(self._evil_student.profile.name, respUnicode)
        self.assertIn(escape(self._evil_student.profile.name), respUnicode)
Exemplo n.º 40
0
    def call_view(self,
                  mock_request,
                  commentable_id,
                  user,
                  group_id,
                  pass_group_id=True):
        mock_request.side_effect = make_mock_request_impl("dummy content")

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().get("dummy_url", data=request_data)
        request.user = user
        mako_middleware_process_request(request)
        return views.forum_form_discussion(
            request, self.course.id.to_deprecated_string())
Exemplo n.º 41
0
    def _test_action(self, action):
        """
        Test for XSS vulnerability in the given action

        Build a request with the given action, call the instructor dashboard
        view, and check that HTML code in a user's name is properly escaped.
        """
        req = self._request_factory.post("dummy_url", data={"action": action})
        req.user = self._instructor
        req.session = {}

        mako_middleware_process_request(req)
        resp = legacy.instructor_dashboard(
            req, self._course.id.to_deprecated_string())
        respUnicode = resp.content.decode(settings.DEFAULT_CHARSET)
        self.assertNotIn(self._evil_student.profile.name, respUnicode)
        self.assertIn(escape(self._evil_student.profile.name), respUnicode)
Exemplo n.º 42
0
    def test_html(self, mock_request):
        self._create_mock_cohorted_thread(mock_request)

        request = RequestFactory().get("dummy_url")
        request.user = self.student
        mako_middleware_process_request(request)
        response = views.single_thread(request,
                                       self.course.id.to_deprecated_string(),
                                       "dummy_discussion_id",
                                       self.mock_thread_id)

        self.assertEquals(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
        html = response.content

        # Verify that the group name is correctly included in the HTML
        self.assertRegexpMatches(
            html, r'&quot;group_name&quot;: &quot;student_cohort&quot;')
Exemplo n.º 43
0
    def setUp(self):
        super(ProgressPageTests, self).setUp()
        self.request_factory = RequestFactory()
        self.user = UserFactory.create()
        self.request = self.request_factory.get("foo")
        self.request.user = self.user

        mako_middleware_process_request(self.request)
        course = CourseFactory.create(
            start=datetime(2013, 9, 16, 7, 17, 28),
            grade_cutoffs={u'çü†øƒƒ': 0.75, 'Pass': 0.5},
        )
        self.course = modulestore().get_course(course.id)
        CourseEnrollmentFactory(user=self.user, course_id=self.course.id)

        self.chapter = ItemFactory.create(category='chapter', parent_location=self.course.location)
        self.section = ItemFactory.create(category='sequential', parent_location=self.chapter.location)
        self.vertical = ItemFactory.create(category='vertical', parent_location=self.section.location)
Exemplo n.º 44
0
    def call_view(self,
                  mock_request,
                  commentable_id,
                  user,
                  group_id,
                  pass_group_id=True):
        mock_request.side_effect = make_mock_request_impl(
            "dummy context", group_id=self.student_cohort.id)

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        request = RequestFactory().get("dummy_url", data=request_data)
        request.user = user
        mako_middleware_process_request(request)
        return views.single_thread(request,
                                   self.course.id.to_deprecated_string(),
                                   "dummy_discussion_id", "dummy_thread_id")
Exemplo n.º 45
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)
Exemplo n.º 46
0
    def test_full_pipeline_succeeds_for_linking_account(self):
        # First, create, the request and strategy that store pipeline state,
        # configure the backend, and mock out wire traffic.
        request, strategy = self.get_request_and_strategy(
            auth_entry=pipeline.AUTH_ENTRY_LOGIN, redirect_uri='social:complete')
        strategy.backend.auth_complete = mock.MagicMock(return_value=self.fake_auth_complete(strategy))
        pipeline.analytics.track = mock.MagicMock()
        request.user = self.create_user_models_for_existing_account(
            strategy, '*****@*****.**', 'password', self.get_username(), skip_social_auth=True)

        # Instrument the pipeline to get to the dashboard with the full
        # expected state.
        self.client.get(
            pipeline.get_login_url(self.PROVIDER_CLASS.NAME, pipeline.AUTH_ENTRY_LOGIN))
        actions.do_complete(strategy, social_views._do_login)  # pylint: disable-msg=protected-access

        mako_middleware_process_request(strategy.request)
        student_views.signin_user(strategy.request)
        student_views.login_user(strategy.request)
        actions.do_complete(strategy, social_views._do_login)  # pylint: disable-msg=protected-access

        # First we expect that we're in the unlinked state, and that there
        # really is no association in the backend.
        self.assert_account_settings_context_looks_correct(account_settings_context(request), request.user, linked=False)
        self.assert_social_auth_does_not_exist_for_user(request.user, strategy)

        # We should be redirected back to the complete page, setting
        # the "logged in" cookie for the marketing site.
        self.assert_logged_in_cookie_redirect(actions.do_complete(
            request.social_strategy, social_views._do_login, request.user, None,  # pylint: disable-msg=protected-access
            redirect_field_name=auth.REDIRECT_FIELD_NAME
        ))

        # Set the cookie and try again
        self.set_logged_in_cookie(request)

        # Fire off the auth pipeline to link.
        self.assert_redirect_to_dashboard_looks_correct(actions.do_complete(
            request.social_strategy, social_views._do_login, request.user, None,  # pylint: disable-msg=protected-access
            redirect_field_name=auth.REDIRECT_FIELD_NAME))

        # Now we expect to be in the linked state, with a backend entry.
        self.assert_social_auth_exists_for_user(request.user, strategy)
        self.assert_account_settings_context_looks_correct(account_settings_context(request), request.user, linked=True)
Exemplo n.º 47
0
    def test_exception_shib_login(self):
        """
        Tests that we get the error page when there is no REMOTE_USER
        or Shib-Identity-Provider in request.META
        """
        no_remote_user_request = self.request_factory.get('/shib-login')
        no_remote_user_request.META.update({'Shib-Identity-Provider': IDP})
        no_remote_user_request.user = AnonymousUser()

        mako_middleware_process_request(no_remote_user_request)
        no_remote_user_response = shib_login(no_remote_user_request)
        self.assertEqual(no_remote_user_response.status_code, 403)
        self.assertIn("identity server did not return your ID information", no_remote_user_response.content)

        no_idp_request = self.request_factory.get('/shib-login')
        no_idp_request.META.update({'REMOTE_USER': REMOTE_USER})
        no_idp_response = shib_login(no_idp_request)
        self.assertEqual(no_idp_response.status_code, 403)
        self.assertIn("identity server did not return your ID information", no_idp_response.content)
Exemplo n.º 48
0
    def test_exception_shib_login(self):
        """
        Tests that we get the error page when there is no REMOTE_USER
        or Shib-Identity-Provider in request.META
        """
        no_remote_user_request = self.request_factory.get('/shib-login')
        no_remote_user_request.META.update({'Shib-Identity-Provider': IDP})
        no_remote_user_request.user = AnonymousUser()

        mako_middleware_process_request(no_remote_user_request)
        no_remote_user_response = shib_login(no_remote_user_request)
        self.assertEqual(no_remote_user_response.status_code, 403)
        self.assertIn("identity server did not return your ID information", no_remote_user_response.content)

        no_idp_request = self.request_factory.get('/shib-login')
        no_idp_request.META.update({'REMOTE_USER': REMOTE_USER})
        no_idp_response = shib_login(no_idp_request)
        self.assertEqual(no_idp_response.status_code, 403)
        self.assertIn("identity server did not return your ID information", no_idp_response.content)
Exemplo n.º 49
0
    def test_html(self, mock_request):
        self._create_mock_cohorted_thread(mock_request)

        request = RequestFactory().get("dummy_url")
        request.user = self.student
        mako_middleware_process_request(request)
        response = views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
            "dummy_discussion_id",
            self.mock_thread_id
        )

        self.assertEquals(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
        html = response.content

        # Verify that the group name is correctly included in the HTML
        self.assertRegexpMatches(html, r'&quot;group_name&quot;: &quot;student_cohort&quot;')
Exemplo n.º 50
0
    def test_ext_auth_password_length_too_short(self):
        """
        Tests that even if password policy is enforced, ext_auth registrations aren't subject to it
        """
        self.url_params['password'] = '******'  # shouldn't pass validation
        request = self.request_factory.post(self.url, self.url_params)
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(external_id='*****@*****.**',
                                  external_email='*****@*****.**',
                                  internal_password=self.url_params['password'],
                                  external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        mako_middleware_process_request(request)
        response = create_account(request)
        self.assertEqual(response.status_code, 200)
        obj = json.loads(response.content)
        self.assertTrue(obj['success'])
Exemplo n.º 51
0
    def verify_end_date(self, course_id, expected_end_text=None):
        """
        Visits the about page for `course_id` and tests that both the text "Classes End", as well
        as the specified `expected_end_text`, is present on the page.

        If `expected_end_text` is None, verifies that the about page *does not* contain the text
        "Classes End".
        """
        request = self.request_factory.get("foo")
        request.user = self.user

        # TODO: Remove the dependency on MakoMiddleware (by making the views explicitly supply a RequestContext)
        mako_middleware_process_request(request)

        result = views.course_about(request, course_id)
        if expected_end_text is not None:
            self.assertContains(result, "Classes End")
            self.assertContains(result, expected_end_text)
        else:
            self.assertNotContains(result, "Classes End")
Exemplo n.º 52
0
    def call_view(self, mock_request, commentable_id, user, group_id, pass_group_id=True, is_ajax=False):
        mock_request.side_effect = make_mock_request_impl("dummy context", group_id=self.student_cohort.id)

        request_data = {}
        if pass_group_id:
            request_data["group_id"] = group_id
        headers = {}
        if is_ajax:
            headers['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
        request = RequestFactory().get(
            "dummy_url",
            data=request_data,
            **headers
        )
        request.user = user
        mako_middleware_process_request(request)
        return views.single_thread(
            request,
            self.course.id.to_deprecated_string(),
            "dummy_discussion_id",
            "dummy_thread_id"
        )
Exemplo n.º 53
0
    def get_response(self, mock_request, params, **headers):
        mock_request.side_effect = make_mock_request_impl(self.TEST_THREAD_TEXT, self.TEST_THREAD_ID)
        request = RequestFactory().get("dummy_url", data=params, **headers)
        request.user = self.student

        mako_middleware_process_request(request)
        response = views.user_profile(request, self.course.id.to_deprecated_string(), self.profiled_user.id)
        mock_request.assert_any_call(
            "get",
            StringEndsWithMatcher("/users/{}/active_threads".format(self.profiled_user.id)),
            data=None,
            params=PartialDictMatcher(
                {
                    "course_id": self.course.id.to_deprecated_string(),
                    "page": params.get("page", 1),
                    "per_page": views.THREADS_PER_PAGE,
                }
            ),
            headers=ANY,
            timeout=ANY,
        )
        return response
    def test_ext_auth_password_length_too_short(self):
        """
        Tests that even if password policy is enforced, ext_auth registrations aren't subject to it
        """
        self.url_params['password'] = '******'  # shouldn't pass validation
        request = self.request_factory.post(self.url, self.url_params)
        # now indicate we are doing ext_auth by setting 'ExternalAuthMap' in the session.
        request.session = import_module(
            settings.SESSION_ENGINE).SessionStore()  # empty session
        extauth = ExternalAuthMap(
            external_id='*****@*****.**',
            external_email='*****@*****.**',
            internal_password=self.url_params['password'],
            external_domain='shib:https://idp.stanford.edu/')
        request.session['ExternalAuthMap'] = extauth
        request.user = AnonymousUser()

        mako_middleware_process_request(request)
        response = create_account(request)
        self.assertEqual(response.status_code, 200)
        obj = json.loads(response.content)
        self.assertTrue(obj['success'])
Exemplo n.º 55
0
    def test_course_about_in_cart(self):
        in_cart_span = '<span class="add-to-cart">'
        # don't mock this course due to shopping cart existence checking
        course = CourseFactory.create(org="new", number="unenrolled", display_name="course")
        request = self.request_factory.get(reverse('about_course', args=[course.id.to_deprecated_string()]))
        request.user = AnonymousUser()
        mako_middleware_process_request(request)
        response = views.course_about(request, course.id.to_deprecated_string())
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(in_cart_span, response.content)

        # authenticated user with nothing in cart
        request.user = self.user
        response = views.course_about(request, course.id.to_deprecated_string())
        self.assertEqual(response.status_code, 200)
        self.assertNotIn(in_cart_span, response.content)

        # now add the course to the cart
        cart = shoppingcart.models.Order.get_cart_for_user(self.user)
        shoppingcart.models.PaidCourseRegistration.add_to_order(cart, course.id)
        response = views.course_about(request, course.id.to_deprecated_string())
        self.assertEqual(response.status_code, 200)
        self.assertIn(in_cart_span, response.content)