示例#1
0
文件: test_views.py 项目: deone/vms
    def test_generate_instant_vouchers_POST(self):
        # Create package
        response = send_api_request(settings.PACKAGE_INSERT_URL,
            data={'package_type': 'Daily', 'volume': '3', 'speed': '1.5', 'price': 4})
        package = response['result']

        self.c.post(reverse('login'), {'username': '******', 'password': '******'})

        factory = RequestFactory()
        session = SessionMiddleware()

        request = factory.post(reverse('vouchers:generate_instant'), data={'package': package['id'], 'quantity': '20'})
        request.user = self.user

        session.process_request(request)
        request.session.save()

        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = generate(request, template='vouchers/generate_instant.html',
            voucher_form=forms.GenerateInstantVoucherForm, redirect_to='vouchers:generate_instant')
        storage = get_messages(request)

        lst = []
        for message in storage:
            lst.append(message)

        self.assertEqual(response.status_code, 302)
        self.assertEqual('Vouchers generated successfully.', lst[0].__str__())
        self.assertEqual(response.get('location'), reverse('vouchers:generate_instant'))

        # Delete package
        send_api_request(settings.PACKAGE_DELETE_URL, data={'package_id': package['id']})
示例#2
0
文件: test_views.py 项目: deone/vms
    def test_generate_standard_vouchers_POST(self):
        self.c.post(reverse('login'), {'username': '******', 'password': '******'})

        factory = RequestFactory()
        session = SessionMiddleware()

        request = factory.post(reverse('vouchers:generate_standard'), data={'price': '1', 'quantity': '20'})
        request.user = self.user

        session.process_request(request)
        request.session.save()

        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = generate(request, template='vouchers/generate_standard.html',
            voucher_form=forms.GenerateStandardVoucherForm, redirect_to='vouchers:generate_standard')
        storage = get_messages(request)

        lst = []
        for message in storage:
            lst.append(message)

        self.assertEqual(response.status_code, 302)
        self.assertEqual('Vouchers generated successfully.', lst[0].__str__())
        self.assertEqual(response.get('location'), reverse('vouchers:generate_standard'))
示例#3
0
 def get_request(self, url='/'):
     request = self.factory.get('/')
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
     request.resolver_match = resolve(url)
     return request
class UtilityTestCase(TestCase):

    def setUp(self):
        self.session_backend = SessionStore()
        self.session_middleware = SessionMiddleware()
        self.factory = RequestFactory()
        self.user = self.create_user('user')
        self.owner = self.create_user('owner')
        self.admin = self.create_user('admin', is_superuser=True)
        self.staff = self.create_user('staff', is_staff=True)
        self.client = Client()

    def create_user(self, username, **attrs):
        user = get_user_model().objects.create_user(
            username,
            username + '@example.com',
            DEFAULT_PASSWORD
        )
        for name, value in attrs.items():
            setattr(user, name, value)
        user.save()
        return user

    def login(self, client, username):
        client.login(username=username, password=DEFAULT_PASSWORD)

    def get_request(self, url=None):
        if url is None:
            url = '/'
        request = self.factory.get(url)
        request.user = AnonymousUser()
        self.session_middleware.process_request(request)
        return request
示例#5
0
    def request(self, **request):
        """
        Rather than issuing a request and returning the response, this
        simply constructs an ``HttpRequest`` object and returns it.

        """
        environ = {
            'HTTP_COOKIE': self.cookies,
            'PATH_INFO': '/',
            'QUERY_STRING': '',
            'REMOTE_ADDR': '127.0.0.1',
            'REQUEST_METHOD': 'GET',
            'SCRIPT_NAME': '',
            'SERVER_NAME': 'testserver',
            'SERVER_PORT': '80',
            'SERVER_PROTOCOL': 'HTTP/1.1',
            'wsgi.version': (1, 0),
            'wsgi.url_scheme': 'http',
            'wsgi.errors': self.errors,
            'wsgi.multiprocess': True,
            'wsgi.multithread': False,
            'wsgi.run_once': False,
            'wsgi.input': None,
        }
        environ.update(self.defaults)
        environ.update(request)
        request = WSGIRequest(environ)

        # We have to manually add a session since we'll be bypassing
        # the middleware chain.
        session_middleware = SessionMiddleware()
        session_middleware.process_request(request)
        return request
示例#6
0
def add_session_to_request(request):
    """
    Annotate a request object with a session
    """
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()
示例#7
0
 def session(self, request):
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
     middleware = AuthenticationMiddleware()
     middleware.process_request(request)
     return request
示例#8
0
class TestUserPreferenceMiddleware(TestCase):
    """
    Tests to make sure user preferences are getting properly set in the middleware
    """

    def setUp(self):
        self.middleware = LanguagePreferenceMiddleware()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.session_middleware.process_request(self.request)

    def test_no_language_set_in_session_or_prefs(self):
        # nothing set in the session or the prefs
        self.middleware.process_request(self.request)
        self.assertNotIn('django_language', self.request.session)

    def test_language_in_user_prefs(self):
        # language set in the user preferences and not the session
        UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)
        self.assertEquals(self.request.session['django_language'], 'eo')

    def test_language_in_session(self):
        # language set in both the user preferences and session,
        # session should get precedence
        self.request.session['django_language'] = 'en'
        UserPreference.set_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)

        self.assertEquals(self.request.session['django_language'], 'en')
示例#9
0
 def do_session_middleware_stuff(self, request):
     """
     If using the RequestFactory, middleware is skipped which breaks auth. Use this to re-add session info to request
     """
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
示例#10
0
    def test_session_delete_on_end(self):
        request = RequestFactory().get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header looks like:
        #  Set-Cookie: sessionid=; expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/
        self.assertEqual(
            'Set-Cookie: {}={}; expires=Thu, 01-Jan-1970 00:00:00 GMT; '
            'Max-Age=0; Path=/'.format(
                settings.SESSION_COOKIE_NAME,
                '""' if sys.version_info >= (3, 5) else '',
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )
示例#11
0
    def request(self, *args, **kwargs):
        """Perform request from factory

        :param method: Request method as string
        :returns: Request instance

        Several additional keywords arguments can be passed in:

        user
            User instance to use for the request, will default to an
            :py:class:`AnonymousUser` instance otherwise.

        session
            Dictionary to instantiate the session handler with.

        Other keyword arguments are passed into the request method
        """
        factory = RequestFactory()
        method = kwargs.pop('method', 'get')
        fn = getattr(factory, method)
        request = fn(*args, **kwargs)

        # Mock user, session, and messages
        request.user = kwargs.pop('user', AnonymousUser())

        session = kwargs.pop('session', {})
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.update(session)

        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        return request
示例#12
0
class TestLangPrefView(TestCase):
    """
    Language preference view tests.
    """

    def setUp(self):
        super(TestLangPrefView, self).setUp()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.session_middleware.process_request(self.request)

    def test_language_session_update(self):
        # test language session updating correctly.
        self.request.session[LANGUAGE_SESSION_KEY] = 'ar'
        response = self.client.patch(reverse("session_language"), json.dumps({'pref-lang': 'eo'}))
        self.assertEqual(response.status_code, 200)
        self.client.get('/')
        self.assertEquals(get_language(), 'eo')

        response = self.client.patch(reverse("session_language"), json.dumps({'pref-lang': 'en'}))
        self.assertEqual(response.status_code, 200)
        self.client.get('/')
        self.assertEquals(get_language(), 'en')
示例#13
0
文件: tests.py 项目: GeyseR/django
    def test_session_delete_on_end_with_custom_domain_and_path(self):
        request = self.request_factory.get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain and path looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0;
        #              Path=/example/
        self.assertEqual(
            'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, '
            '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )
示例#14
0
 def get_request(self, method=RequestFactory().get, ajax=False, data=None,
                 user=AnonymousUser(), add_session=False, session_dict={},
                 view_kwargs=None, **kwargs):
     if data is not None:
         kwargs.update({'data': data})
     req = method(self.get_url(view_kwargs=view_kwargs), **kwargs)
     req.user = user
     # the messages framework only works with the FallbackStorage in case of
     # requestfactory tests
     if add_session:
         middleware = SessionMiddleware()
         middleware.process_request(req)
         req.session.save()
     else:
         setattr(req, 'session', {})
     if session_dict:
         for var in session_dict:
             req.session[var] = session_dict[var]
     messages = FallbackStorage(req)
     setattr(req, '_messages', messages)
     if ajax:
         req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
     req = self.setUpRequest(req)
     if req is None:
         raise RuntimeError(
             'The request has become None. You probably forgot to return'
             ' the request again, when implementing `setUpRequest`.')
     return req
示例#15
0
    def request(self, **request):
        """
        Rather than issuing a request and returning the response, this
        simply constructs an ``HttpRequest`` object and returns it.
        
        """
        environ = {
            "HTTP_COOKIE": self.cookies,
            "PATH_INFO": "/",
            "QUERY_STRING": "",
            "REMOTE_ADDR": "127.0.0.1",
            "REQUEST_METHOD": "GET",
            "SCRIPT_NAME": "",
            "SERVER_NAME": "testserver",
            "SERVER_PORT": "80",
            "SERVER_PROTOCOL": "HTTP/1.1",
            "wsgi.version": (1, 0),
            "wsgi.url_scheme": "http",
            "wsgi.errors": self.errors,
            "wsgi.multiprocess": True,
            "wsgi.multithread": False,
            "wsgi.run_once": False,
        }
        environ.update(self.defaults)
        environ.update(request)
        request = WSGIRequest(environ)

        # We have to manually add a session since we'll be bypassing
        # the middleware chain.
        session_middleware = SessionMiddleware()
        session_middleware.process_request(request)
        return request
示例#16
0
文件: tests.py 项目: nim65s/django
    def test_session_delete_on_end_with_custom_domain(self):
        request = RequestFactory().get("/")
        response = HttpResponse("Session test")
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = "abc"

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # Check that the cookie was deleted, not recreated.
        # A deleted cookie header with a custom domain looks like:
        #  Set-Cookie: sessionid=; Domain=.example.local;
        #              expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/
        self.assertEqual(
            "Set-Cookie: {}={}; Domain=.example.local; expires=Thu, "
            "01-Jan-1970 00:00:00 GMT; Max-Age=0; Path=/".format(
                settings.SESSION_COOKIE_NAME, '""' if sys.version_info >= (3, 5) else ""
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME]),
        )
示例#17
0
    def test_user_can_only_select_journal_contacts(self):
        """ Test list of contacts

        Make sure the list contains all the contacts of the publisher
        and only that """
        request = self.factory.get(
            reverse('userspace:journal:editor:add'), args=(self.journal.pk, ))
        request.user = self.user
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        view = IssueSubmissionCreate(request=request, journal_pk=self.journal.pk)
        view.current_journal = self.journal
        form = view.get_form()

        user_contacts = set(User.objects.filter(
            journals=self.user.journals.all()
        ).distinct())

        form_contacts = set(
            form.fields['contact'].queryset
        )

        self.assertEquals(
            user_contacts,
            form_contacts
        )
示例#18
0
    def setUp(self):
        self.mk_main()
        self.request = RequestFactory().get('/')
        self.request.user = self.login()
        session_middleware = SessionMiddleware()
        session_middleware.process_request(self.request)
        self.request.session.save()

        self.section = SectionPage(title='test section')
        self.section_index.add_child(instance=self.section)

        self.important_tag = Tag(title='important tag')
        self.another_tag = Tag(title='other tag')
        self.tags = [self.important_tag, self.another_tag]
        for tag in self.tags:
            self.tag_index.add_child(instance=tag)
            tag.save_revision()

        self.page = ArticlePage(title='test article')
        self.section.add_child(instance=self.page)
        self.page.save_revision()

        for tag in self.tags:
            ArticlePageTags.objects.create(
                tag=tag,
                page=self.page,
            )

        self.adapter = PersistentSurveysSegmentsAdapter(self.request)
示例#19
0
文件: tests.py 项目: nim65s/django
    def test_empty_session_saved(self):
        """
        If a session is emptied of data but still has a key, it should still
        be updated.
        """
        request = RequestFactory().get("/")
        response = HttpResponse("Session test")
        middleware = SessionMiddleware()

        # Set a session key and some data.
        middleware.process_request(request)
        request.session["foo"] = "bar"
        # Handle the response through the middleware.
        response = middleware.process_response(request, response)
        self.assertEqual(tuple(request.session.items()), (("foo", "bar"),))
        # A cookie should be set, along with Vary: Cookie.
        self.assertIn("Set-Cookie: sessionid=%s" % request.session.session_key, str(response.cookies))
        self.assertEqual(response["Vary"], "Cookie")

        # Empty the session data.
        del request.session["foo"]
        # Handle the response through the middleware.
        response = HttpResponse("Session test")
        response = middleware.process_response(request, response)
        self.assertEqual(dict(request.session.values()), {})
        session = Session.objects.get(session_key=request.session.session_key)
        self.assertEqual(session.get_decoded(), {})
        # While the session is empty, it hasn't been flushed so a cookie should
        # still be set, along with Vary: Cookie.
        self.assertGreater(len(request.session.session_key), 8)
        self.assertIn("Set-Cookie: sessionid=%s" % request.session.session_key, str(response.cookies))
        self.assertEqual(response["Vary"], "Cookie")
示例#20
0
class UtilityTestCase(TestCase):

    def setUp(self):
        self.session_backend = SessionStore()
        self.session_middleware = SessionMiddleware()
        self.factory = RequestFactory()
        self.user = self.create_user('user')
        self.admin = self.create_user('admin', is_superuser=True)
        self.staff = self.create_user('staff', is_staff=True)
        self.client = Client()

    def create_user(self, username, **attrs):
        if attrs is None:
            attrs = {}
        user = User.objects.create_user(username, username + '@example.com', DEFAULT_PASSWORD)
        user.profile = Profile.objects.create(user=user)
        user.__dict__.update(**attrs)
        user.backend = self.session_backend
        user.save()
        return user

    def login(self, client, username):
        client.login(username=username, password=DEFAULT_PASSWORD)

    def get_request_for_user(self, user):
        request = self.factory.get('/')
        request.user = self.user
        self.session_middleware.process_request(request)
        logout(request)
        return request
示例#21
0
    def test_set_language(self):

        request = self.factory.post('/languages/',
                                    json.dumps({'lang': 'ru'}),
                                    content_type="application/json")
        smiddleware = SessionMiddleware()
        lmiddleware = LocaleMiddleware()
        smiddleware.process_request(request)
        lmiddleware.process_request(request)
        request.session.save()

        response = LanguagesView.as_view()(request)

        lmiddleware.process_response(request, response)

        self.assertEqual(response.status_code, 200)

        response_content = response.content

        if six.PY3:
            response_content = str(response_content, encoding='utf8')

        self.assertJSONEqual(response_content, {u'success': True})

        self.assertEqual(response['Content-Language'], u'ru')
示例#22
0
    def test_session_delete_on_end(self):
        request = self.request_factory.get('/')
        response = HttpResponse('Session test')
        middleware = SessionMiddleware()

        # Before deleting, there has to be an existing cookie
        request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc'

        # Simulate a request that ends the session
        middleware.process_request(request)
        request.session.flush()

        # Handle the response through the middleware
        response = middleware.process_response(request, response)

        # The cookie was deleted, not recreated.
        # A deleted cookie header looks like:
        #  Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/
        self.assertEqual(
            'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; '
            'Max-Age=0; Path=/'.format(
                settings.SESSION_COOKIE_NAME,
            ),
            str(response.cookies[settings.SESSION_COOKIE_NAME])
        )
        # SessionMiddleware sets 'Vary: Cookie' to prevent the 'Set-Cookie'
        # from being cached.
        self.assertEqual(response['Vary'], 'Cookie')
class InviteAcceptViewTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.session_middleware = SessionMiddleware()

    def _add_session(self, request):
        self.session_middleware.process_request(request)

    def test_context_data__no_invite(self):
        view = InviteAcceptView()
        view.invite = None
        view.content = None
        view.request = RequestFactory().get('/')
        context = view.get_context_data()
        self.assertIsNone(context['invite'])
        self.assertIsNone(context['content'])
        self.assertFalse(context['invited_person_exists'])
        self.assertFalse(context['sender_display'])
        self.assertFalse(context['invited_person_exists'])

    def test_invite(self):
        view = InviteAcceptView()
        event = EventFactory()
        invite = InviteFactory(content_id=event.pk, kind=EventInvite.slug, user=PersonFactory(first_name="Conan", last_name="O'Brien"))
        view.content = event
        view.request = RequestFactory().get('/')
        view.request.user = PersonFactory(email=invite.email, confirmed_email=invite.email)
        self._add_session(view.request)
        with mock.patch.object(wraps=Order.objects.for_request, target=Order.objects, attribute='for_request') as for_request:
            view.get(view.request, code=invite.code)
        for_request.assert_called_once_with(create=True, request=view.request, event=view.content)
        orders = Order.objects.all()
        self.assertEqual(len(orders), 1)
        self.assertEqual(orders[0].person, view.request.user)
示例#24
0
class SignedCookiesTest(TestCase):
    def setUp(self):
        self.middleware = SignedCookiesMiddleware()
        self.auth_middleware = AuthenticationMiddleware()
        self.session_middleware = SessionMiddleware()
        
    def _process_request(self, request):
        self.session_middleware.process_request(request)
        self.auth_middleware.process_request(request)
        self.middleware.process_request(request)
        
    def _process_response(self, request, response):
        self.middleware.process_response(request, response)
        self.session_middleware.process_response(request, response)
        
    def test_middleware(self):
        request = HttpRequest()
        
        request.COOKIES['key'] = 'foo'
        self._process_request(request)
        self.failIf('key' in request.COOKIES)
        
        response = HttpResponse()
        request = HttpRequest()
        self._process_request(request)
        response.set_cookie('key', 'foo')
        self._process_response(request, response)
        signed_val = response.cookies['key'].value
        self.failIfEqual(signed_val, 'foo')
        
        request.COOKIES['key'] = signed_val
        self._process_request(request)
        self.failUnlessEqual(request.COOKIES['key'], 'foo')
示例#25
0
    def test_can_render_a_list_of_forums_according_to_their_minimum_tree_level(self):
        # Setup
        forums = Forum.objects.all()

        request = self.request_factory.get('/')
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()

        request.user = self.user
        ForumPermissionMiddleware().process_request(request)
        t = Template(self.loadstatement + '{% forum_list forums %}')
        c = Context({'forums': forums, 'request': request})
        expected_out = render_to_string(
            'machina/forum/forum_list.html',
            {
                'forums': forums,
                'user': self.user,
                'root_level': 0,
                'root_level_middle': 1,
                'root_level_sub': 2,
            }
        )
        # Run
        rendered = t.render(c)
        # Check
        assert rendered != ''
        assert rendered == expected_out
示例#26
0
def should_completely_remove_data_from_database_when_deleted():
    middleware = SessionMiddleware()

    # Do an initial request, to add some data to the storage
    request, response = factory.get('/'), HttpResponse('')
    middleware.process_request(request)
    # The session key isn't actually determined until the session is used (it's
    # all lazy), so we'll set some test data initially that we can then use
    # later.
    request.session['some other data'] = 'testing'
    storage = DatabaseStorage('name', 'namespace')
    storage.process_request(request)
    step = storage['step1']
    step.data = {'blarg': 'bloog'}
    storage.process_response(response)
    middleware.process_response(request, response)
    session_key = request.session.session_key  # save for later request
    assert WizardState.objects.filter(name='name', namespace='namespace').count() == 1

    # check deletion
    request = factory.get('/')
    request.COOKIES[settings.SESSION_COOKIE_NAME] = session_key  # use session
    middleware.process_request(request)
    storage = DatabaseStorage('name', 'namespace')
    storage.process_request(request)
    storage.delete()
    #storage.process_response(HttpResponse(''))
    assert WizardState.objects.filter(name='name', namespace='namespace').count() == 0
    assert request.session['some other data'] == 'testing'
示例#27
0
def should_raise_exception_if_session_middleware_not_used():
    class Step1(forms.Form):
        name = forms.CharField()

    class Step2(forms.Form):
        name = forms.CharField()

    class StepsWizardView(WizardView):
        # pylint: ignore=W0223
        storage = 'formwizard.storage.SessionStorage'
        steps = (
            ("Step 1", Step1),
            ("Step 2", Step2),
        )
        template_name = 'simple.html'

    view = StepsWizardView.as_view()
    request = factory.get('/')
    with Assert.raises(ImproperlyConfigured):
        view(request)

    # use session middleware and no exceptions should be raised
    middleware = SessionMiddleware()
    request = factory.get('/')
    middleware.process_request(request)
    view(request)
示例#28
0
	def test_auth_false(self):
		request = self.factory.post('/auth_view/',{'username':'******','password':'******'})
		middleware = SessionMiddleware()
		middleware.process_request(request)
		request.session.save()
		response=auth_view(request)
		self.assertEqual(response.status_code, 200)
		self.assertEqual(response.content,'invalid')
示例#29
0
文件: tests.py 项目: GeyseR/django
 def test_samesite_session_cookie(self):
     request = self.request_factory.get('/')
     response = HttpResponse()
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session['hello'] = 'world'
     response = middleware.process_response(request, response)
     self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict')
示例#30
0
def gen_request_with_session(factory):
    session_middleware = SessionMiddleware();
    request = factory.get('/auth/test');
    
    session_middleware.process_request(request);
    request.session.save();
    
    return request;
示例#31
0
    def test_learner_flow_different_user_creation(self):
        """
        Test different user creation.
        """
        mock_request = RequestFactory().post(
            '',
            data={
                'oauth_nonce': 'oauth_nonce',
                'oauth_consumer_key': self.lti_lms_platform.consumer_key,
                'roles': 'Learner',
                'user_id': 'user_id',
                'context_id': 'some+course+id'
            }
        )
        middleware = SessionMiddleware()
        middleware.process_request(mock_request)
        mock_request.session.save()

        tool_provider = DjangoToolProvider.from_django_request(request=mock_request)

        count_of_the_sequence = Sequence.objects.all().count()
        count_of_lti_users = LtiUser.objects.all().count()

        # learner_flow is called 2 times (here and below) to ensure that implement logic works correctly

        learner_flow(
            mock_request,
            self.lti_lms_platform,
            tool_provider,
            self.collection_order1.slug,
        )
        learner_flow(
            mock_request,
            self.lti_lms_platform,
            tool_provider,
            self.collection_order1.slug,
        )
        self.assertEqual(Sequence.objects.all().count(), count_of_the_sequence + 1)

        count_of_the_sequence += 1

        learner_flow(
            mock_request,
            self.lti_lms_platform,
            tool_provider,
            self.collection_order1.slug,
            'marker',
        )
        learner_flow(
            mock_request,
            self.lti_lms_platform,
            tool_provider,
            self.collection_order1.slug,
            'marker',
        )
        self.assertEqual(Sequence.objects.all().count(), count_of_the_sequence + 1)

        count_of_the_sequence += 1
        learner_flow(
            mock_request,
            self.lti_lms_platform,
            tool_provider,
            self.collection_order1.slug,
            'marker1',
        )
        learner_flow(
            mock_request,
            self.lti_lms_platform,
            tool_provider,
            self.collection_order1.slug,
            'marker2',
        )
        self.assertEqual(Sequence.objects.all().count(), count_of_the_sequence + 2)

        # Ensure that only one LTI user was created.
        self.assertEqual(LtiUser.objects.all().count(), count_of_lti_users + 1)
示例#32
0
 def setUp(self):
     self.req = RequestFactory().get("/")
     middleware = SessionMiddleware()
     middleware.process_request(self.req)
     self.req.session.save()
示例#33
0
class OrderManagerTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.session_middleware = SessionMiddleware()

    def _add_session(self, request):
        self.session_middleware.process_request(request)

    def test_for_request__code__anon_anon(self):
        """Anonymous users forbidden to access anonymous orders."""
        event = EventFactory()
        OrderFactory(event=event, person=None)
        request = self.factory.get('/')
        self._add_session(request)
        request.user = AnonymousUser()
        with self.assertRaises(Order.DoesNotExist):
            Order.objects.for_request(event, request, create=False)

    def test_for_request__code__authed_anon(self):
        """Authenticated users cannot access orders created by anonymous users
        without the code stored in the session.
        """
        event = EventFactory()
        person = PersonFactory()
        OrderFactory(event=event, person=None)
        request = self.factory.get('/')
        self._add_session(request)
        request.user = person
        with self.assertRaises(Order.DoesNotExist):
            Order.objects.for_request(event, request, create=False)

    def test_for_request__code__anon_authed(self):
        """An anonymous user can't access an order created by an authenticated
        user.
        """
        event = EventFactory()
        person = PersonFactory()
        order = OrderFactory(event=event, person=person)
        request = self.factory.get('/')
        self._add_session(request)
        Order.objects._set_session_code(request, event, order.code)
        request.user = AnonymousUser()
        with self.assertRaises(Order.DoesNotExist):
            Order.objects.for_request(event, request, create=False)

    def test_for_request__code__authed_other_authed(self):
        """An authenticated user can't access orders created by anyone else."""
        event = EventFactory()
        person = PersonFactory()
        person2 = PersonFactory()
        order = OrderFactory(event=event, person=person2)
        request = self.factory.get('/')
        self._add_session(request)
        Order.objects._set_session_code(request, event, order.code)
        request.user = person
        with self.assertRaises(Order.DoesNotExist):
            Order.objects.for_request(event, request, create=False)

    def test_for_request__authed(self):
        """An authenticated user will automatically get their own order."""
        event = EventFactory()
        person = PersonFactory()
        order = OrderFactory(event=event, person=person)
        request = self.factory.get('/')
        request.user = person
        fetched, created = Order.objects.for_request(event,
                                                     request,
                                                     create=False)
        self.assertFalse(created)
        self.assertEqual(fetched, order)

    def test_for_request__session__anon_anon(self):
        """An anonymous user can have their order stored in the session."""
        event = EventFactory()
        order = OrderFactory(event=event, person=None)
        request = self.factory.get('/')
        self._add_session(request)
        Order.objects._set_session_code(request, event, order.code)
        request.user = AnonymousUser()

        fetched, created = Order.objects.for_request(event,
                                                     request,
                                                     create=False)
        self.assertFalse(created)
        self.assertEqual(fetched, order)

    def test_for_request__session__authed_anon(self):
        """
        An authenticated user can auto-claim a session-stored order.
        """
        event = EventFactory()
        person = PersonFactory()
        order = OrderFactory(event=event, person=None)
        request = self.factory.get('/')
        self._add_session(request)
        Order.objects._set_session_code(request, event, order.code)
        request.user = person

        fetched, created = Order.objects.for_request(event,
                                                     request,
                                                     create=False)
        self.assertFalse(created)
        self.assertEqual(fetched, order)
        self.assertEqual(fetched.person_id, person.id)

    def test_for_request__session__authed_anon__with_order(self):
        """
        An authenticated user's own order will take precedence over
        a session order.
        """
        event = EventFactory()
        person = PersonFactory()
        order = OrderFactory(event=event, person=None)
        order2 = OrderFactory(event=event, person=person)
        request = self.factory.get('/')
        self._add_session(request)
        Order.objects._set_session_code(request, event, order.code)
        request.user = person

        fetched, created = Order.objects.for_request(event,
                                                     request,
                                                     create=False)
        self.assertFalse(created)
        self.assertEqual(fetched, order2)

    def test_for_request__create__anon(self):
        """
        An anonymous user will get a new order back if no code is provided
        and no session code is available, but create is True.
        """
        event = EventFactory()
        request = self.factory.get('/')
        request.user = AnonymousUser()
        self._add_session(request)
        fetched, created = Order.objects.for_request(event,
                                                     request,
                                                     create=True)
        self.assertTrue(created)
        self.assertEqual(fetched.code,
                         Order.objects._get_session_code(request, event))
        self.assertIsNone(fetched.person)

    def test_for_request__create__authed(self):
        """
        An authenticated user will get a new order back if no code is provided
        and no session code is available, but create is True.
        """
        event = EventFactory()
        person = PersonFactory()
        request = self.factory.get('/')
        request.user = person
        self._add_session(request)
        fetched, created = Order.objects.for_request(event,
                                                     request,
                                                     create=True)
        self.assertTrue(created)
        self.assertIsNone(Order.objects._get_session_code(request, event))
        self.assertEqual(fetched.person_id, person.id)
def add_session(req):
    mw = SessionMiddleware()
    mw.process_request(req)
    req.session.save()
示例#35
0
def http_request():
    request = HttpRequest()
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    return request
示例#36
0
def with_session(request):
    """Annotate a request object with a session"""
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()
    return request
def test_form_wizard_returns_failure_by_option(rf, law_case_factory,
                                               questionaire_factory):
    class TestWizardView(FormWizardView):
        def get_lawcase(self):
            return LawCase.objects.all().first()

    law_case = law_case_factory()
    qn_1 = questionaire_factory(law_case=law_case, order=1)
    q1 = Question.add_root(**(get_single_option_question(questionaire=qn_1)))
    q2 = q1.add_child(**(get_single_option_question(questionaire=qn_1)))

    Condition.objects.create(question=q2,
                             if_option='is',
                             if_value='no',
                             then_value='failure')

    request = rf.get('/')
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    request.session.save()
    response = TestWizardView.as_view()(request)
    assert 'legal_advice_builder/form_wizard.html' in response.template_name
    assert response.context_data.get(
        'form').fields['question'].initial == q1.id
    dict_as_choices = [(k, v) for k, v in q1.options.items()]
    assert response.context_data.get(
        'form').fields['option'].choices == dict_as_choices

    praefix = 'legal_advice_builder_{}'.format(law_case.id)

    session_data = response._request.session.get(praefix)
    assert json.loads(response._request.session.get(praefix)).get(
        'current_questionaire') == qn_1.id
    assert json.loads(response._request.session.get(praefix)).get(
        'current_question') == q1.id
    assert json.loads(
        response._request.session.get(praefix)).get('answers') == []

    data = {'question': q1.id, 'option': 'yes'}

    request = rf.post('/', data)
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    request.session.save()
    request.session[praefix] = session_data
    response = TestWizardView.as_view()(request)

    assert 'legal_advice_builder/form_wizard.html' in response.template_name
    assert response.context_data.get(
        'form').fields['question'].initial == q2.id
    assert json.loads(response._request.session.get(praefix)).get(
        'current_questionaire') == qn_1.id
    assert json.loads(response._request.session.get(praefix)).get(
        'current_question') == q2.id
    assert json.loads(
        response._request.session.get(praefix)).get('answers') == [{
            'option':
            'yes',
            'question':
            '1'
        }]

    session_data = response._request.session.get(praefix)

    data = {'question': q2.id, 'option': 'no'}

    request = rf.post('/', data)
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    request.session.save()
    request.session[praefix] = session_data
    response = TestWizardView.as_view()(request)

    assert 'legal_advice_builder/form_wizard.html' in response.template_name
    assert response.context_data.get('failure') is True
    assert response.context_data.get('form') is None
示例#38
0
class CountryMiddlewareTests(TestCase):
    """
    Tests of CountryMiddleware.
    """
    def setUp(self):
        self.country_middleware = CountryMiddleware()
        self.session_middleware = SessionMiddleware()
        self.authenticated_user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory.create()
        self.request_factory = RequestFactory()
        self.patcher = patch.object(pygeoip.GeoIP, 'country_code_by_addr',
                                    self.mock_country_code_by_addr)
        self.patcher.start()

    def tearDown(self):
        self.patcher.stop()

    def mock_country_code_by_addr(self, ip_addr):
        """
        Gives us a fake set of IPs
        """
        ip_dict = {
            '117.79.83.1': 'CN',
            '117.79.83.100': 'CN',
            '4.0.0.0': 'SD',
            '2001:da8:20f:1502:edcf:550b:4a9c:207d': 'CN',
        }
        return ip_dict.get(ip_addr, 'US')

    def test_country_code_added(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='117.79.83.1',
        )
        request.user = self.authenticated_user
        self.session_middleware.process_request(request)
        # No country code exists before request.
        self.assertNotIn('country_code', request.session)
        self.assertNotIn('ip_address', request.session)
        self.country_middleware.process_request(request)
        # Country code added to session.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('117.79.83.1', request.session.get('ip_address'))

    def test_ip_address_changed(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='4.0.0.0',
        )
        request.user = self.anonymous_user
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # Country code is changed.
        self.assertEqual('SD', request.session.get('country_code'))
        self.assertEqual('4.0.0.0', request.session.get('ip_address'))

    def test_ip_address_is_not_changed(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='117.79.83.1',
        )
        request.user = self.anonymous_user
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # Country code is not changed.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('117.79.83.1', request.session.get('ip_address'))

    def test_same_country_different_ip(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='117.79.83.100',
        )
        request.user = self.anonymous_user
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # Country code is not changed.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('117.79.83.100', request.session.get('ip_address'))

    def test_ip_address_is_none(self):
        # IP address is not defined in request.
        request = self.request_factory.get('/somewhere')
        request.user = self.anonymous_user
        # Run process_request to set up the session in the request
        # to be able to override it.
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # No country code exists after request processing.
        self.assertNotIn('country_code', request.session)
        self.assertNotIn('ip_address', request.session)

    def test_ip_address_is_ipv6(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='2001:da8:20f:1502:edcf:550b:4a9c:207d')
        request.user = self.authenticated_user
        self.session_middleware.process_request(request)
        # No country code exists before request.
        self.assertNotIn('country_code', request.session)
        self.assertNotIn('ip_address', request.session)
        self.country_middleware.process_request(request)
        # Country code added to session.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('2001:da8:20f:1502:edcf:550b:4a9c:207d',
                         request.session.get('ip_address'))
示例#39
0
def process_request(request):
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()
示例#40
0
class TestUserPreferenceMiddleware(TestCase):
    """
    Tests to make sure user preferences are getting properly set in the middleware.
    """

    def setUp(self):
        super(TestUserPreferenceMiddleware, self).setUp()
        self.middleware = LanguagePreferenceMiddleware()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0'  # pylint: disable=no-member
        self.session_middleware.process_request(self.request)

    def test_logout_shouldnt_remove_cookie(self):

        self.middleware.process_request(self.request)

        self.request.user = self.anonymous_user

        response = mock.Mock(spec=HttpResponse)
        self.middleware.process_response(self.request, response)

        response.delete_cookie.assert_not_called()

    @ddt.data(None, 'es', 'en')
    def test_preference_setting_changes_cookie(self, lang_pref_out):
        """
        Test that the LANGUAGE_COOKIE is always set to the user's current language preferences
        at the end of the request, with an expiry that's the same as the users current session cookie.
        """
        if lang_pref_out:
            set_user_preference(self.user, LANGUAGE_KEY, lang_pref_out)
        else:
            delete_user_preference(self.user, LANGUAGE_KEY)

        response = mock.Mock(spec=HttpResponse)
        self.middleware.process_response(self.request, response)

        if lang_pref_out:
            response.set_cookie.assert_called_with(
                settings.LANGUAGE_COOKIE,
                value=lang_pref_out,
                domain=settings.SESSION_COOKIE_DOMAIN,
                max_age=COOKIE_DURATION,
            )
        else:
            response.delete_cookie.assert_called_with(
                settings.LANGUAGE_COOKIE,
                domain=settings.SESSION_COOKIE_DOMAIN,
            )

        self.assertNotIn(LANGUAGE_SESSION_KEY, self.request.session)

    @ddt.data(*itertools.product(
        (None, 'eo', 'es'),  # LANGUAGE_COOKIE
        (None, 'es', 'en'),  # Language Preference In
    ))
    @ddt.unpack
    @mock.patch('openedx.core.djangoapps.lang_pref.middleware.set_user_preference')
    def test_preference_cookie_changes_setting(self, lang_cookie, lang_pref_in, mock_set_user_preference):
        self.request.COOKIES[settings.LANGUAGE_COOKIE] = lang_cookie

        if lang_pref_in:
            set_user_preference(self.user, LANGUAGE_KEY, lang_pref_in)
        else:
            delete_user_preference(self.user, LANGUAGE_KEY)

        self.middleware.process_request(self.request)

        if lang_cookie is None:
            self.assertEqual(mock_set_user_preference.mock_calls, [])
        else:
            mock_set_user_preference.assert_called_with(self.user, LANGUAGE_KEY, lang_cookie)

    @ddt.data(*(
        (logged_in, ) + test_def
        for logged_in in (True, False)
        for test_def in [
            # (LANGUAGE_COOKIE, LANGUAGE_SESSION_KEY, Accept-Language In, Accept-Language Out)
            (None, None, None, None),
            (None, 'eo', None, None),
            (None, 'eo', 'en', 'en'),
            (None, None, 'en', 'en'),
            ('en', None, None, 'en'),
            ('en', None, 'eo', 'en;q=1.0,eo'),
            ('en', None, 'en', 'en'),
            ('en', 'eo', 'en', 'en'),
            ('en', 'eo', 'eo', 'en;q=1.0,eo')
        ]
    ))
    @ddt.unpack
    def test_preference_cookie_overrides_browser(self, logged_in, lang_cookie, lang_session, accept_lang_in, accept_lang_out):
        if not logged_in:
            self.request.user = self.anonymous_user
        if lang_cookie:
            self.request.COOKIES[settings.LANGUAGE_COOKIE] = lang_cookie
        if lang_session:
            self.request.session[LANGUAGE_SESSION_KEY] = lang_session
        if accept_lang_in:
            self.request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang_in
        else:
            del self.request.META['HTTP_ACCEPT_LANGUAGE']

        self.middleware.process_request(self.request)

        accept_lang_result = self.request.META.get('HTTP_ACCEPT_LANGUAGE')
        if accept_lang_result:
            accept_lang_result = parse_accept_lang_header(accept_lang_result)

        if accept_lang_out:
            accept_lang_out = parse_accept_lang_header(accept_lang_out)

        if accept_lang_out and accept_lang_result:
            self.assertItemsEqual(accept_lang_result, accept_lang_out)
        else:
            self.assertEqual(accept_lang_result, accept_lang_out)

        self.assertEquals(self.request.session.get(LANGUAGE_SESSION_KEY), lang_session)

    @ddt.data(None, 'es', 'en')
    def test_logout_preserves_cookie(self, lang_cookie):
        if lang_cookie:
            self.client.cookies[settings.LANGUAGE_COOKIE] = lang_cookie
        elif settings.LANGUAGE_COOKIE in self.client.cookies:
            del self.client.cookies[settings.LANGUAGE_COOKIE]
        # Use an actual call to the logout endpoint, because the logout function
        # explicitly clears all cookies
        self.client.get(reverse('logout'))
        if lang_cookie:
            self.assertEqual(
                self.client.cookies[settings.LANGUAGE_COOKIE].value,
                lang_cookie
            )
        else:
            self.assertNotIn(settings.LANGUAGE_COOKIE, self.client.cookies)

    def test_process_response_no_user_noop(self):
        del self.request.user
        response = mock.Mock(spec=HttpResponse)

        result = self.middleware.process_response(self.request, response)

        self.assertIs(result, response)
        self.assertEqual(response.mock_calls, [])

    def test_preference_update_noop(self):
        self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'es'

        # No preference yet, should write to the database

        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), None)

        with self.assertNumQueries(5):
            self.middleware.process_request(self.request)

        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'es')

        response = mock.Mock(spec=HttpResponse)

        with self.assertNumQueries(1):
            self.middleware.process_response(self.request, response)

        # Preference is the same as the cookie, shouldn't write to the database

        with self.assertNumQueries(3):
            self.middleware.process_request(self.request)

        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'es')

        response = mock.Mock(spec=HttpResponse)

        with self.assertNumQueries(1):
            self.middleware.process_response(self.request, response)

        # Cookie changed, should write to the database again

        self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'en'

        with self.assertNumQueries(5):
            self.middleware.process_request(self.request)

        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'en')

        with self.assertNumQueries(1):
            self.middleware.process_response(self.request, response)
示例#41
0
 def get_request(self, data):
     request = RequestFactory().post(path='/', data=data)
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
     return request
示例#42
0
class CountryMiddlewareTests(TestCase):
    """
    Tests of CountryMiddleware.
    """
    def setUp(self):
        super(CountryMiddlewareTests, self).setUp()  # lint-amnesty, pylint: disable=super-with-arguments
        self.country_middleware = CountryMiddleware()
        self.session_middleware = SessionMiddleware()
        self.authenticated_user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory.create()
        self.request_factory = RequestFactory()
        patcher = patch.object(maxminddb, 'open_database')
        patcher.start()
        country_patcher = patch.object(geoip2.database.Reader, 'country', self.mock_country)
        country_patcher.start()
        self.addCleanup(patcher.stop)
        self.addCleanup(country_patcher.stop)

    def mock_country(self, ip_address):
        """
        :param ip_address:
        :return:
        """
        ip_dict = {
            '117.79.83.1': 'CN',
            '117.79.83.100': 'CN',
            '4.0.0.0': 'SD',
            '2001:da8:20f:1502:edcf:550b:4a9c:207d': 'CN',
        }

        magic_mock = MagicMock()
        magic_mock.country = MagicMock()
        type(magic_mock.country).iso_code = PropertyMock(return_value=ip_dict.get(ip_address))

        return magic_mock

    def test_country_code_added(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='117.79.83.1',
        )
        request.user = self.authenticated_user
        self.session_middleware.process_request(request)
        # No country code exists before request.
        self.assertNotIn('country_code', request.session)
        self.assertNotIn('ip_address', request.session)
        self.country_middleware.process_request(request)
        # Country code added to session.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('117.79.83.1', request.session.get('ip_address'))

    def test_ip_address_changed(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='4.0.0.0',
        )
        request.user = self.anonymous_user
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # Country code is changed.
        self.assertEqual('SD', request.session.get('country_code'))
        self.assertEqual('4.0.0.0', request.session.get('ip_address'))

    def test_ip_address_is_not_changed(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='117.79.83.1',
        )
        request.user = self.anonymous_user
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # Country code is not changed.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('117.79.83.1', request.session.get('ip_address'))

    def test_same_country_different_ip(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='117.79.83.100',
        )
        request.user = self.anonymous_user
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # Country code is not changed.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual('117.79.83.100', request.session.get('ip_address'))

    def test_ip_address_is_none(self):
        # IP address is not defined in request.
        request = self.request_factory.get('/somewhere')
        request.user = self.anonymous_user
        # Run process_request to set up the session in the request
        # to be able to override it.
        self.session_middleware.process_request(request)
        request.session['country_code'] = 'CN'
        request.session['ip_address'] = '117.79.83.1'
        self.country_middleware.process_request(request)
        # No country code exists after request processing.
        self.assertNotIn('country_code', request.session)
        self.assertNotIn('ip_address', request.session)

    def test_ip_address_is_ipv6(self):
        request = self.request_factory.get(
            '/somewhere',
            HTTP_X_FORWARDED_FOR='2001:da8:20f:1502:edcf:550b:4a9c:207d'
        )
        request.user = self.authenticated_user
        self.session_middleware.process_request(request)
        # No country code exists before request.
        self.assertNotIn('country_code', request.session)
        self.assertNotIn('ip_address', request.session)
        self.country_middleware.process_request(request)
        # Country code added to session.
        self.assertEqual('CN', request.session.get('country_code'))
        self.assertEqual(
            '2001:da8:20f:1502:edcf:550b:4a9c:207d', request.session.get('ip_address'))
示例#43
0
 def build_dummy_request_with_session_handling(self):
     dummy_request = self.factory.get(reverse('login'))
     session_middleware = SessionMiddleware()
     session_middleware.process_request(dummy_request)
     dummy_request.session.save()
     return dummy_request
示例#44
0
 def add_session_to_request(request):
     """Use SessionMiddleware to add a session to the request."""
     """Annotate a request object with a session"""
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
def test_form_wizard_update_answer_for_download(rf, law_case_factory,
                                                questionaire_factory,
                                                answer_factory):
    class TestWizardView(FormWizardView):
        def get_lawcase(self):
            return LawCase.objects.all().first()

    lc = law_case_factory(allow_download=True)
    qn1 = questionaire_factory(success_message='Success qn1', law_case=lc)
    qn2 = questionaire_factory(success_message='Success qn2', law_case=lc)
    q1 = Question.add_root(**get_single_option_question(questionaire=qn1))
    q2 = q1.add_child(**get_single_option_question(questionaire=qn1))
    Condition.objects.create(question=q2,
                             if_option='is',
                             if_value='yes',
                             then_value='success')
    Condition.objects.create(question=q2,
                             if_option='is',
                             if_value='no',
                             then_value='failure')
    q3 = Question.add_root(**get_single_option_question(questionaire=qn2))

    answer = answer_factory()
    answers = [{
        'question': q1.id,
        'option': 'yes'
    }, {
        'question': q2.id,
        'option': 'yes'
    }, {
        'question': q3.id,
        'option': 'yes'
    }]
    answer.answers = answers
    answer.save()

    data = {'answer_id': answer.id, 'download': 'pdf'}
    request = rf.post('/', data)
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    praefix = 'legal_advice_builder_{}'.format(lc.id)
    request.session[praefix] = json.dumps(
        {
            'current_question': q3.id,
            'answers': answers
        }, cls=DjangoJSONEncoder)
    request.session.save()
    resp = TestWizardView.as_view()(request)
    assert resp['content-type'] == 'application/pdf'

    data = {'answer_id': answer.id}
    request = rf.post('/', data)
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    praefix = 'legal_advice_builder_{}'.format(lc.id)
    request.session[praefix] = json.dumps(
        {
            'current_question': q3.id,
            'answers': answers
        }, cls=DjangoJSONEncoder)
    request.session.save()
    resp = TestWizardView.as_view()(request)

    lc.allow_download = False
    lc.save()

    data = {'answer_id': answer.id, 'download': 'pdf'}
    request = rf.post('/', data)
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(request)
    praefix = 'legal_advice_builder_{}'.format(lc.id)
    request.session[praefix] = json.dumps(
        {
            'current_question': q3.id,
            'answers': answers
        }, cls=DjangoJSONEncoder)
    request.session.save()
    resp = TestWizardView.as_view()(request)
    assert resp.status_code == 405
示例#46
0
class ProfileTests(TestCase):
    def setUp(self) -> None:
        self.factory = RequestFactory()
        self.middleware = SessionMiddleware()

        User = get_user_model()
        self.test_user = User.objects.create_user(username='******',
                                                  email='*****@*****.**',
                                                  password='******')
        # signals create profile
        self.profile = Profile.objects.get(user=self.test_user.id)

    def test_profile_creation_with_signals(self):
        self.assertEqual(self.profile.user.username, 'testuser1')
        self.assertEqual(self.profile.user.email, '*****@*****.**')
        self.assertEqual(self.profile.user.profile, self.profile)

    def test_profile_str(self):
        self.assertEqual(str(self.profile), 'testuser1 Profile')

    def test_profile_image(self):
        profile_image = SimpleUploadedFile(
            name='test_image.jpg',
            content=open('media/images/profiles/test.jpg', 'rb').read(),
            content_type='image/jpeg')
        profile_image.height = 1000
        profile_image.width = 100

        self.profile.image = profile_image
        self.profile.save()

        self.assertTrue(self.profile.image.height <= 500)
        self.assertTrue(self.profile.image.width <= 500)

    def test_profile_update_view(self):
        # login
        self.client.post(reverse('account_login'), {
            'login': '******',
            'password': '******'
        },
                         follow=False)

        response = self.client.get(reverse('profile'))
        self.assertTrue(response.context['form_user'])
        self.assertTrue(response.context['form_profile'])

        # post
        with open('media/images/profiles/test.jpg', 'rb') as img:
            request = self.factory.post(reverse('profile'),
                                        data={
                                            'email': '*****@*****.**',
                                            'username': '******',
                                            'image': img
                                        })
            request.user = self.test_user
            response = ProfileUpdate.as_view()(request)
            self.test_user.refresh_from_db()

            self.assertEqual(response.status_code, 302)
            self.assertEqual(self.test_user.email, '*****@*****.**')
            self.assertEqual(self.test_user.username, 'newUsername')

    def test_profile_update_view_failed_form(self):
        # login
        self.client.post(reverse('account_login'), {
            'login': '******',
            'password': '******'
        },
                         follow=False)

        request = self.factory.post(reverse('profile'), data={'email': 1111})
        request.user = self.test_user
        self.middleware.process_request(request)
        request.session.save()
        response = ProfileUpdate.as_view()(request)
        self.test_user.refresh_from_db()

        self.assertEqual(response.status_code, 200)
        self.assertEqual(self.test_user.email, '*****@*****.**')
示例#47
0
 def _add_session(request):
     """Annotate the request object with a session"""
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
class TestUserPreferenceMiddleware(unittest.TestCase):
    """
    Tests to make sure language configured by the `default_language` column on EnterpriseCustomer is being used.
    """

    def setUp(self):
        """
        Setup middleware, request, session, user and enterprise customer for tests. Also mock imports from edx-platform.
        """
        self.mock_imports()

        super().setUp()
        self.middleware = EnterpriseLanguagePreferenceMiddleware()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0'
        self.session_middleware.process_request(self.request)
        self.client = Client()
        self.enterprise_customer = EnterpriseCustomerFactory()
        self.enterprise_customer_user = EnterpriseCustomerUserFactory(
            enterprise_customer=self.enterprise_customer,
            user_id=self.user.id,
        )

    def mock_imports(self):
        """
        Mock all the imports from edx-platform
        """
        mocks = [
            mock.patch('enterprise.middleware.LANGUAGE_KEY', LANGUAGE_KEY),
            mock.patch('enterprise.middleware.UserAPIInternalError', UserAPIInternalError),
            mock.patch('enterprise.middleware.UserAPIRequestError', UserAPIRequestError),
            mock.patch('enterprise.middleware.get_user_preference', mock.MagicMock(return_value=None)),
            mock.patch('enterprise.middleware.is_request_from_mobile_app', mock.MagicMock(return_value=False)),
            mock.patch('enterprise.utils.UserPreference', mock.MagicMock()),

        ]
        for mock_object in mocks:
            self.jwt_builder = mock_object.start()
            self.addCleanup(mock_object.stop)

    @ddt.data(None, 'es', 'en')
    def test_preference_setting_changes_cookie(self, lang_pref_out):
        """
        Validate that the language set via enterprise customer's `default_language`
        column is used as the learner's default language.
        """
        self.enterprise_customer.default_language = lang_pref_out
        self.enterprise_customer.save()
        self.middleware.process_request(self.request)

        assert getattr(self.request, '_anonymous_user_cookie_lang', None) == lang_pref_out
        assert LANGUAGE_SESSION_KEY not in self.request.session

    def test_real_user_extracted_from_request(self):
        """
        Validate the the real_user is used in cases where user is masquerading as someone else.
        """
        # Hide the real user and masquerade as a fake user, fake user does not belong to any enterprise customer.
        self.request.user = UserFactory()
        self.request.user.real_user = self.user

        self.middleware.process_request(self.request)

        # Make sure the real user is used for setting the language cookie
        assert getattr(self.request, '_anonymous_user_cookie_lang', None) == self.enterprise_customer.default_language
        assert LANGUAGE_SESSION_KEY not in self.request.session

    def test_cookie_not_set_for_anonymous_user(self):
        """
        Validate the language cookie is not set if the request user is not authenticated.
        """
        # Hide the real user and masquerade as a fake user, fake user does not belong to any enterprise customer.
        self.request.user = self.anonymous_user
        self.middleware.process_request(self.request)

        # Make sure the set cookie is not called for anonymous users
        assert getattr(self.request, '_anonymous_user_cookie_lang', None) is None
        assert LANGUAGE_SESSION_KEY not in self.request.session

    def test_cookie_not_set_for_non_enterprise_learners(self):
        """
        Validate the language cookie is not set if the request user does not belong to any enterprise customer.
        """
        # Hide the real user and masquerade as a fake user, fake user does not belong to any enterprise customer.
        self.request.user = UserFactory()
        self.middleware.process_request(self.request)

        # Make sure the set cookie is not called for anonymous users
        assert getattr(self.request, '_anonymous_user_cookie_lang', None) is None
        assert LANGUAGE_SESSION_KEY not in self.request.session

    def test_cookie_when_there_is_no_request_user(self):
        """
        Validate the language cookie is not set if, for some reason, the request user is not present.
        """
        # Hide the real user and masquerade as a fake user, fake user does not belong to any enterprise customer.
        request = RequestFactory().get('/somewhere')
        session_middleware = SessionMiddleware()
        session_middleware.process_request(request)

        self.middleware.process_request(request)

        # Make sure the set cookie is not called for anonymous users
        assert getattr(self.request, '_anonymous_user_cookie_lang', None) is None
        assert LANGUAGE_SESSION_KEY not in self.request.session

    def test_errors_are_handled(self):
        """
        Validate that the errors raised when querying user preference are handled correctly.
        In this case those errors are ignored.
        """
        with mock.patch('enterprise.middleware.get_user_preference') as mock_get_user_preference:
            mock_get_user_preference.side_effect = UserAPIInternalError
            self.middleware.process_request(self.request)

            # Make sure the set cookie is not called for anonymous users
            # pylint: disable=protected-access,no-member
            assert self.request._anonymous_user_cookie_lang == self.enterprise_customer.default_language
            assert LANGUAGE_SESSION_KEY not in self.request.session

    def test_cookie_not_set_for_mobile_requests(self):
        """
        Validate the language cookie is not set if the request is coming from the mobile app.
        """
        with mock.patch('enterprise.middleware.is_request_from_mobile_app') as mock_is_request_from_mobile_app:
            mock_is_request_from_mobile_app.return_value = True
            self.middleware.process_request(self.request)

            # Make sure the set cookie is not called for anonymous users
            assert getattr(self.request, '_anonymous_user_cookie_lang', None) is None
            assert LANGUAGE_SESSION_KEY not in self.request.session
示例#49
0
class TestProcedures(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.middleware = SessionMiddleware()
        self.user = User.objects.create_superuser('testuser',
                                                  '*****@*****.**',
                                                  'supersecretpass')
        self.user.save()

        # Creating procedures for testing the ability to add them to a roadmap
        request = self.factory.post(
            'create/', {
                'procedure_name': 'Object One',
                'notes': 'These are test notes',
                'time_frame': 'days',
                'time': '22'
            })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        new_procedure(request)
        self.test_object_one = Procedure.objects.get(
            procedure_name='Object One', procedure_info='These are test notes')

        # Creating procedures for testing the ability to add them to a roadmap
        request = self.factory.post(
            'create/', {
                'procedure_name': 'Object Two',
                'notes': 'These are test notes',
                'time_frame': 'days',
                'time': '22'
            })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        new_procedure(request)
        self.test_object_two = Procedure.objects.get(
            procedure_name='Object Two', procedure_info='These are test notes')

        # Creating procedures for testing the ability to add them to a roadmap
        request = self.factory.post(
            'create/', {
                'procedure_name': 'Object Three',
                'notes': 'These are test notes',
                'time_frame': 'days',
                'time': '22'
            })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        new_procedure(request)
        self.test_object_three = Procedure.objects.get(
            procedure_name='Object Three',
            procedure_info='These are test notes')

        request = self.factory.post('/roadmaps/create/', {
            'roadmap_name': 'Test Roadmap',
            'time_frame': 'days',
            'time': '22'
        })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        create_roadmap(request)
        self.test_roadmap = Roadmap.objects.get(roadmap_name='Test Roadmap')

    def test_get_roadmaps(self):
        request = self.factory.get('/roadmaps/')
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = roadmaps_index(request)
        self.assertEqual(response.status_code, 200)

    def test_post_roadmaps(self):
        request = self.factory.post('/roadmaps/')
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = roadmaps_index(request)
        self.assertEqual(response.status_code, 302)

    def test_get_create_roadmap(self):
        request = self.factory.get('/roadmaps/create/')
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = create_roadmap(request)
        self.assertEqual(response.status_code, 200)

    def test_create_roadmap_valid(self):
        request = self.factory.post('/roadmaps/create/', {
            'roadmap_name': 'Created Roadmap',
            'time_frame': 'days',
            'time': '22'
        })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = create_roadmap(request)
        self.assertEqual(response.status_code, 302)

        test_roadmap = Roadmap.objects.get(roadmap_name='Created Roadmap')
        self.assertIsNotNone(test_roadmap)

    def test_create_roadmap_invalid(self):
        request = self.factory.post('/roadmaps/create/', {})
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = create_roadmap(request)
        self.assertEqual(response.status_code, 302)

    def test_get_view_roadmap_valid(self):
        request = self.factory.get('/roadmaps/view_roadmap/?id=' +
                                   str(self.test_roadmap.id))
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = view_roadmap(request)

        self.assertEqual(response.status_code, 200)

    def test_get_view_roadmap_invalid(self):
        request = self.factory.get('/roadmaps/view_roadmap/?id=' +
                                   str(self.test_roadmap.id + 99999))
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = view_roadmap(request)

        self.assertEqual(response.status_code, 302)

    def test_get_modify_roadmap_valid(self):
        request = self.factory.get(
            '/roadmaps/view_roadmap/modify_roadmap/?id=' +
            str(self.test_roadmap.id))
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = modify_roadmap(request)

        self.assertEqual(response.status_code, 200)

    def test_get_modify_roadmap_invalid(self):
        request = self.factory.get(
            '/roadmaps/view_roadmap/modify_roadmap/?id=' +
            str(self.test_roadmap.id + 99999))
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = modify_roadmap(request)

        self.assertEqual(response.status_code, 302)

    def test_add_to_roadmap(self):
        expected_list = [(self.test_object_one, 1), (self.test_object_two, 1),
                         (self.test_object_three, 1)]

        add_request = self.factory.post(
            '/roadmaps/view_roadmap/add/?id=' + str(self.test_roadmap.id), {
                'procedure': [
                    self.test_object_one.id, self.test_object_two.id,
                    self.test_object_three.id
                ],
                'phase':
                1
            })

        add_request.user = self.user
        self.middleware.process_request(add_request)
        add_request.session.save()

        response = add_to_roadmap(add_request)

        self.assertEqual(response.status_code, 302)

        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

    def test_add_to_roadmap_invalid_id(self):
        expected_list = []

        add_request = self.factory.post(
            '/roadmaps/view_roadmap/add/?id=' + str(99999), {
                'procedure': [
                    self.test_object_one.id, self.test_object_two.id,
                    self.test_object_three.id
                ],
                'phase':
                1
            })

        add_request.user = self.user
        self.middleware.process_request(add_request)
        add_request.session.save()

        setattr(add_request, 'session', 'session')
        messages = FallbackStorage(add_request)
        setattr(add_request, '_messages', messages)

        response = add_to_roadmap(add_request)

        self.assertEqual(response.status_code, 302)

        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

    def test_add_to_roadmap_invalid_form(self):
        expected_list = []

        add_request = self.factory.post(
            '/roadmaps/view_roadmap/add/?id=' + str(self.test_roadmap.id), {
                'procedure': [
                    self.test_object_one.id, self.test_object_two.id,
                    self.test_object_three.id
                ]
            })

        add_request.user = self.user
        self.middleware.process_request(add_request)
        add_request.session.save()

        setattr(add_request, 'session', 'session')
        messages = FallbackStorage(add_request)
        setattr(add_request, '_messages', messages)

        response = add_to_roadmap(add_request)

        self.assertEqual(response.status_code, 302)

        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

    def test_remove_from_roadmap(self):
        self.test_add_to_roadmap()

        # Remove procedure one and three from the roadmap
        remove_request = self.factory.post(
            '/roadmaps/view_roadmap/remove/?id=' + str(self.test_roadmap.id),
            {'selection[]': ['1,1', '3,1']})

        remove_request.user = self.user
        self.middleware.process_request(remove_request)

        response = remove_selected_pairs(remove_request)

        self.assertEqual(response.status_code, 302)

        expected_list = [(self.test_object_two, 1)]

        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

    def test_remove_nothing_from_roadmap(self):
        self.test_add_to_roadmap()

        # Remove procedure one and three from the roadmap
        remove_request = self.factory.post(
            '/roadmaps/view_roadmap/remove/?id=' + str(self.test_roadmap.id),
            {'selection[]': []})

        remove_request.user = self.user
        self.middleware.process_request(remove_request)

        response = remove_selected_pairs(remove_request)

        self.assertEqual(response.status_code, 302)

        expected_list = [(self.test_object_one, 1), (self.test_object_two, 1),
                         (self.test_object_three, 1)]

        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

    def test_remove_from_roadmap_invalid_roadmap_id(self):
        self.test_add_to_roadmap()

        # Remove procedure one and three from the roadmap
        remove_request = self.factory.post(
            '/roadmaps/view_roadmap/remove/?id=' + str(99999),
            {'selection[]': ['1,1', '3,1']})

        remove_request.user = self.user
        self.middleware.process_request(remove_request)

        setattr(remove_request, 'session', 'session')
        messages = FallbackStorage(remove_request)
        setattr(remove_request, '_messages', messages)

        response = remove_selected_pairs(remove_request)

        self.assertEqual(response.status_code, 302)

        expected_list = [(self.test_object_one, 1), (self.test_object_two, 1),
                         (self.test_object_three, 1)]

        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

    def test_delete_roadmap(self):
        self.test_add_to_roadmap()

        # Delete the roadmap
        delete_request = self.factory.post(
            '/roadmaps/view_roadmap/delete/?id=' + str(self.test_roadmap.id),
            {'item_name': str(self.test_roadmap.roadmap_name)})

        delete_request.user = self.user
        self.middleware.process_request(delete_request)

        response = delete_roadmap(delete_request)

        self.assertEqual(response.status_code, 302)

        expected_list = []

        # Assert there are no procedure-phase pairs since they've been deleted
        self.assertListEqual(
            expected_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

        # Assert the roadmap itself no longer exists
        self.assertListEqual(
            expected_list,
            list(Roadmap.objects.filter(id=self.test_roadmap.id)))

    def test_delete_roadmap_name_mismatch(self):
        self.test_add_to_roadmap()

        # Delete the roadmap
        delete_request = self.factory.post(
            '/roadmaps/view_roadmap/delete/?id=' + str(self.test_roadmap.id),
            {'item_name': str(self.test_roadmap.roadmap_name) + "bad text"})

        delete_request.user = self.user
        self.middleware.process_request(delete_request)

        setattr(delete_request, 'session', 'session')
        messages = FallbackStorage(delete_request)
        setattr(delete_request, '_messages', messages)

        response = delete_roadmap(delete_request)

        self.assertEqual(response.status_code, 302)

        expected_pair_list = [(self.test_object_one, 1),
                              (self.test_object_two, 1),
                              (self.test_object_three, 1)]

        expected_roadmap_list = [self.test_roadmap]

        # Assert there are no procedure-phase pairs since they've been deleted
        self.assertListEqual(
            expected_pair_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

        # Assert the roadmap itself no longer exists
        self.assertListEqual(
            expected_roadmap_list,
            list(Roadmap.objects.filter(id=self.test_roadmap.id)))

    def test_delete_roadmap_invalid_form(self):
        self.test_add_to_roadmap()

        # Delete the roadmap
        delete_request = self.factory.post(
            '/roadmaps/view_roadmap/delete/?id=' + str(self.test_roadmap.id),
            {})

        delete_request.user = self.user
        self.middleware.process_request(delete_request)

        setattr(delete_request, 'session', 'session')
        messages = FallbackStorage(delete_request)
        setattr(delete_request, '_messages', messages)

        response = delete_roadmap(delete_request)

        self.assertEqual(response.status_code, 302)

        expected_pair_list = [(self.test_object_one, 1),
                              (self.test_object_two, 1),
                              (self.test_object_three, 1)]

        expected_roadmap_list = [self.test_roadmap]

        # Assert there are no procedure-phase pairs since they've been deleted
        self.assertListEqual(
            expected_pair_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

        # Assert the roadmap itself no longer exists
        self.assertListEqual(
            expected_roadmap_list,
            list(Roadmap.objects.filter(id=self.test_roadmap.id)))

    def test_delete_roadmap_invalid_roadmap_id(self):
        self.test_add_to_roadmap()

        # Delete the roadmap
        delete_request = self.factory.post(
            '/roadmaps/view_roadmap/delete/?id=' + str(99999),
            {'item_name': str(self.test_roadmap.roadmap_name)})

        delete_request.user = self.user
        self.middleware.process_request(delete_request)

        setattr(delete_request, 'session', 'session')
        messages = FallbackStorage(delete_request)
        setattr(delete_request, '_messages', messages)

        response = delete_roadmap(delete_request)

        self.assertEqual(response.status_code, 302)

        expected_pair_list = [(self.test_object_one, 1),
                              (self.test_object_two, 1),
                              (self.test_object_three, 1)]

        expected_roadmap_list = [self.test_roadmap]

        # Assert there are no procedure-phase pairs since they've been deleted
        self.assertListEqual(
            expected_pair_list,
            RoadmapProcedureLink.get_procedures_from_roadmap(
                self.test_roadmap))

        # Assert the roadmap itself no longer exists
        self.assertListEqual(
            expected_roadmap_list,
            list(Roadmap.objects.filter(id=self.test_roadmap.id)))

    def test_update_roadmap_valid(self):
        request = self.factory.post(
            '/roadmaps/view_roadmap/update/?id=' + str(self.test_roadmap.id), {
                'roadmap_name': 'Updated Roadmap',
                'time_frame': 'days',
                'time': '22'
            })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        response = update_roadmap(request)
        self.assertEqual(response.status_code, 302)

        test_roadmap = Roadmap.objects.get(roadmap_name='Updated Roadmap')
        self.assertIsNotNone(test_roadmap)

    def test_update_roadmap_invalid_form(self):
        request = self.factory.post(
            '/roadmaps/view_roadmap/update/?id=' + str(self.test_roadmap.id), {
                'roadmap_name': 'Updated Roadmap',
                'time': '22'
            })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = update_roadmap(request)
        self.assertEqual(response.status_code, 302)

        # If an entry exists, it will overwrite None, thus failing the test
        try:
            test_roadmap = None
            test_roadmap = Roadmap.objects.get(roadmap_name='Updated Roadmap')
        except Roadmap.DoesNotExist:
            self.assertIsNone(test_roadmap)

    def test_update_roadmap_valid_invalid_roadmap_id(self):
        request = self.factory.post(
            '/roadmaps/view_roadmap/update/?id=' + str(99999), {
                'roadmap_name': 'Updated Roadmap',
                'time_frame': 'days',
                'time': '22'
            })
        request.user = self.user
        self.middleware.process_request(request)
        request.session.save()

        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)

        response = update_roadmap(request)
        self.assertEqual(response.status_code, 302)

        # If an entry exists, it will overwrite None, thus failing the test
        try:
            test_roadmap = None
            test_roadmap = Roadmap.objects.get(roadmap_name='Updated Roadmap')
        except Roadmap.DoesNotExist:
            self.assertIsNone(test_roadmap)
示例#50
0
 def get_request(self, url='/'):
     request = self.request_factory.get('/')
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
     return request
示例#51
0
class TestUserPreferenceMiddleware(TestCase):
    """
    Tests to make sure user preferences are getting properly set in the middleware.
    """

    def setUp(self):
        super(TestUserPreferenceMiddleware, self).setUp()
        self.middleware = LanguagePreferenceMiddleware()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0'  # pylint: disable=no-member
        self.session_middleware.process_request(self.request)

    def test_no_language_set_in_session_or_prefs(self):
        # nothing set in the session or the prefs
        self.middleware.process_request(self.request)
        self.assertNotIn(LANGUAGE_SESSION_KEY, self.request.session)  # pylint: disable=no-member

    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.released_languages',
        mock.Mock(return_value=[('eo', 'esperanto')])
    )
    def test_language_in_user_prefs(self):
        # language set in the user preferences and not the session
        set_user_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)
        self.assertEquals(self.request.session[LANGUAGE_SESSION_KEY], 'eo')  # pylint: disable=no-member

    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.released_languages',
        mock.Mock(return_value=[('en', 'english'), ('eo', 'esperanto')])
    )
    def test_language_in_session(self):
        # language set in both the user preferences and session,
        # preference should get precedence. The session will hold the last value,
        # which is probably the user's last preference. Look up the updated preference.

        # Dark lang middleware should run after this middleware, so it can
        # set a session language as an override of the user's preference.
        self.request.session[LANGUAGE_SESSION_KEY] = 'en'  # pylint: disable=no-member
        set_user_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)

        self.assertEquals(self.request.session[LANGUAGE_SESSION_KEY], 'eo')  # pylint: disable=no-member

    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.released_languages',
        mock.Mock(return_value=[('eo', 'dummy Esperanto'), ('ar', 'arabic'), ('eu-es', 'euskara (Espainia)')])
    )
    @ddt.data('ar;q=1.0', 'eu;q=1.0', 'es-419;q=1.0')
    def test_browser_language_in_session_for_unauthenticated_user(self, accept_language):
        """
        test: browser language should not be set in user session for unauthenticated user.
        """
        self.request.META['HTTP_ACCEPT_LANGUAGE'] = accept_language  # pylint: disable=no-member
        self.request.user = self.anonymous_user
        self.middleware.process_request(self.request)
        self.assertNotIn(LANGUAGE_SESSION_KEY, self.request.session)   # pylint: disable=no-member

    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.released_languages',
        mock.Mock(return_value=[('en', 'english')])
    )
    def test_browser_language_not_be_in_session(self):
        """
        test: browser language should not be set in user session if it is not supported by system.
        """
        self.request.user = self.anonymous_user
        self.middleware.process_request(self.request)
        self.assertNotEqual(self.request.session.get(LANGUAGE_SESSION_KEY), 'ar')   # pylint: disable=no-member

    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.released_languages',
        mock.Mock(return_value=[('en', 'english'), ('ar', 'arabic')])
    )
    def test_delete_user_lang_preference_not_supported_by_system(self):
        """
        test: user preferred language has been removed from user preferences model if it is not supported by system
        for authenticated users.
        """
        set_user_preference(self.user, LANGUAGE_KEY, 'eo')
        self.middleware.process_request(self.request)
        self.assertEqual(get_user_preference(self.request.user, LANGUAGE_KEY), None)
示例#52
0
def _get_request_with_session_setted(pre_request):
    middleware = SessionMiddleware(dummy_get_response)
    middleware.process_request(pre_request)
    pre_request.session.save()
    return pre_request
示例#53
0
class FacebookCanvasMiddlewareTest(FacebookTest):
    def setUp(self):
        super(FacebookCanvasMiddlewareTest, self).setUp()
        self.factory = RequestFactory()
        self.middleware = FacebookCanvasMiddleWare()
        self.session_middleware = SessionMiddleware()

    def get_canvas_url(self, data={}):
        request = self.factory.post('/', data)
        request.META['HTTP_REFERER'] = 'https://apps.facebook.com/canvas/'
        self.session_middleware.process_request(request)
        return request

    def test_referer(self):
        # test empty referer
        request = self.factory.get('/')
        self.assertIsNone(self.middleware.process_request(request))
        # test referer not facebook
        request = self.factory.get('/')
        request.META['HTTP_REFERER'] = 'https://*****:*****@patch.object(FacebookAuthorization, 'parse_signed_data')
    def test_non_auth_user(
            self, mocked_method=FacebookAuthorization.parse_signed_data):
        mocked_method.return_value = {}
        data = {
            'signed_request':
            'dXairHLF8dfUKaL7ZFXaKmTsAglg0EkyHesTLnPcPAE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImlzc3VlZF9hdCI6MTM1ODA2MTU1MSwidXNlciI6eyJjb3VudHJ5IjoiYnIiLCJsb2NhbGUiOiJlbl9VUyIsImFnZSI6eyJtaW4iOjIxfX19'
        }
        request = self.get_canvas_url(data=data)
        response = self.middleware.process_request(request)
        self.assertTrue(mocked_method.called)
        self.assertIsInstance(response, ScriptRedirect)

    @patch('django_facebook.middleware.connect_user', fake_connect)
    @patch.object(OpenFacebook, 'permissions')
    @patch.object(FacebookAuthorization, 'parse_signed_data')
    def test_auth_user(self,
                       mocked_method_1=FacebookAuthorization.parse_signed_data,
                       mocked_method_2=OpenFacebook.permissions):
        data = {
            'signed_request':
            'd7JQQIfxHgEzLIqJMeU9J5IlLg7shzPJ8DFRF55L52w.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEzNTgwNzQ4MDAsImlzc3VlZF9hdCI6MTM1ODA2ODU1MCwib2F1dGhfdG9rZW4iOiJBQUFGdk02MWpkT0FCQVBhWkNzR1pDM0dEVFZtdDJCWkFQVlpDc0F0aGNmdXBYUnhMN1cwUHBaQm53OEUwTzBBRVNYNjVaQ0JHdjZpOFRBWGhnMEpzbER5UmtmZUlnYnNHUmV2eHQxblFGZ0hNcFNpeTNWRTB3ZCIsInVzZXIiOnsiY291bnRyeSI6ImJyIiwibG9jYWxlIjoiZW5fVVMiLCJhZ2UiOnsibWluIjoyMX19LCJ1c2VyX2lkIjoiMTAwMDA1MDEyNDY2Nzg1In0'
        }
        request = self.get_canvas_url(data=data)
        request.user = AnonymousUser()
        mocked_method_1.return_value = {
            'user_id': '123456',
            'oauth_token': 'qwertyuiop'
        }
        mocked_method_2.return_value = facebook_settings.FACEBOOK_DEFAULT_SCOPE
        self.assertIsNone(self.middleware.process_request(request))
        self.assertTrue(mocked_method_1.called)
class TestUserPreferenceMiddleware(CacheIsolationTestCase):
    """
    Tests to make sure user preferences are getting properly set in the middleware.
    """
    def setUp(self):
        super(TestUserPreferenceMiddleware, self).setUp()
        self.middleware = LanguagePreferenceMiddleware()
        self.session_middleware = SessionMiddleware()
        self.user = UserFactory.create()
        self.anonymous_user = AnonymousUserFactory()
        self.request = RequestFactory().get('/somewhere')
        self.request.user = self.user
        self.request.META['HTTP_ACCEPT_LANGUAGE'] = 'ar;q=1.0'
        self.session_middleware.process_request(self.request)
        self.client = Client()

    def test_logout_shouldnt_remove_cookie(self):

        self.middleware.process_request(self.request)

        self.request.user = self.anonymous_user

        response = mock.Mock(spec=HttpResponse)
        self.middleware.process_response(self.request, response)

        response.delete_cookie.assert_not_called()

    @ddt.data(None, 'es', 'en')
    def test_preference_setting_changes_cookie(self, lang_pref_out):
        """
        Test that the LANGUAGE_COOKIE is always set to the user's current language preferences
        at the end of the request, with an expiry that's the same as the users current session cookie.
        """
        if lang_pref_out:
            set_user_preference(self.user, LANGUAGE_KEY, lang_pref_out)
        else:
            delete_user_preference(self.user, LANGUAGE_KEY)

        response = mock.Mock(spec=HttpResponse)
        self.middleware.process_response(self.request, response)

        if lang_pref_out:
            response.set_cookie.assert_called_with(
                settings.LANGUAGE_COOKIE,
                value=lang_pref_out,
                domain=settings.SESSION_COOKIE_DOMAIN,
                max_age=COOKIE_DURATION,
                secure=self.request.is_secure(),
            )
        else:
            response.delete_cookie.assert_called_with(
                settings.LANGUAGE_COOKIE,
                domain=settings.SESSION_COOKIE_DOMAIN,
            )

        self.assertNotIn(LANGUAGE_SESSION_KEY, self.request.session)

    @ddt.data(*itertools.product(
        (None, 'eo', 'es'),  # LANGUAGE_COOKIE
        (None, 'es', 'en'),  # Language Preference In
    ))
    @ddt.unpack
    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.set_user_preference')
    def test_preference_cookie_changes_setting(self, lang_cookie, lang_pref_in,
                                               mock_set_user_preference):
        self.request.COOKIES[settings.LANGUAGE_COOKIE] = lang_cookie

        if lang_pref_in:
            set_user_preference(self.user, LANGUAGE_KEY, lang_pref_in)
        else:
            delete_user_preference(self.user, LANGUAGE_KEY)

        self.middleware.process_request(self.request)

        if lang_cookie is None:
            self.assertEqual(mock_set_user_preference.mock_calls, [])
        else:
            mock_set_user_preference.assert_called_with(
                self.user, LANGUAGE_KEY, lang_cookie)

    @ddt.data(*(
        (logged_in, ) + test_def for logged_in in (True, False)
        for test_def in [
            # (LANGUAGE_COOKIE, LANGUAGE_SESSION_KEY, Accept-Language In,
            #  Accept-Language Out, Session Lang Out)
            (None, None, None, None, None),
            (None, 'eo', None, None, 'eo'),
            (None, 'en', None, None, 'en'),
            (None, 'eo', 'en', 'en', 'eo'),
            (None, None, 'en', 'en', None),
            ('en', None, None, 'en', None),
            ('en', 'en', None, 'en', 'en'),
            ('en', None, 'eo', 'en;q=1.0,eo', None),
            ('en', None, 'en', 'en', None),
            ('en', 'eo', 'en', 'en', None),
            ('en', 'eo', 'eo', 'en;q=1.0,eo', None)
        ]))
    @ddt.unpack
    def test_preference_cookie_overrides_browser(
        self,
        logged_in,
        lang_cookie,
        lang_session_in,
        accept_lang_in,
        accept_lang_out,
        lang_session_out,
    ):
        if not logged_in:
            self.request.user = self.anonymous_user
        if lang_cookie:
            self.request.COOKIES[settings.LANGUAGE_COOKIE] = lang_cookie
        if lang_session_in:
            self.request.session[LANGUAGE_SESSION_KEY] = lang_session_in
        if accept_lang_in:
            self.request.META['HTTP_ACCEPT_LANGUAGE'] = accept_lang_in
        else:
            del self.request.META['HTTP_ACCEPT_LANGUAGE']

        self.middleware.process_request(self.request)

        accept_lang_result = self.request.META.get('HTTP_ACCEPT_LANGUAGE')
        if accept_lang_result:
            accept_lang_result = parse_accept_lang_header(accept_lang_result)

        if accept_lang_out:
            accept_lang_out = parse_accept_lang_header(accept_lang_out)

        if accept_lang_out and accept_lang_result:
            six.assertCountEqual(self, accept_lang_result, accept_lang_out)
        else:
            self.assertEqual(accept_lang_result, accept_lang_out)

        self.assertEqual(self.request.session.get(LANGUAGE_SESSION_KEY),
                         lang_session_out)

    @ddt.data(None, 'es', 'en')
    def test_logout_preserves_cookie(self, lang_cookie):
        if lang_cookie:
            self.client.cookies[settings.LANGUAGE_COOKIE] = lang_cookie
        elif settings.LANGUAGE_COOKIE in self.client.cookies:
            del self.client.cookies[settings.LANGUAGE_COOKIE]
        # Use an actual call to the logout endpoint, because the logout function
        # explicitly clears all cookies
        self.client.get(reverse('logout'))
        if lang_cookie:
            self.assertEqual(
                self.client.cookies[settings.LANGUAGE_COOKIE].value,
                lang_cookie)
        else:
            self.assertNotIn(settings.LANGUAGE_COOKIE, self.client.cookies)

    @ddt.data((None, None), ('es', 'es-419'), ('en', 'en'),
              ('es-419', 'es-419'))
    @ddt.unpack
    def test_login_captures_lang_pref(self, lang_cookie, expected_lang):
        if lang_cookie:
            self.client.cookies[settings.LANGUAGE_COOKIE] = lang_cookie
        elif settings.LANGUAGE_COOKIE in self.client.cookies:
            del self.client.cookies[settings.LANGUAGE_COOKIE]

        # Use an actual call to the login endpoint, to validate that the middleware
        # stack does the right thing
        response = self.client.post(
            reverse('user_api_login_session'),
            data={
                'email': self.user.email,
                'password': UserFactory._DEFAULT_PASSWORD,  # pylint: disable=protected-access
                'remember': True,
            })

        self.assertEqual(response.status_code, 200)

        if lang_cookie:
            self.assertEqual(response['Content-Language'], expected_lang)
            self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY),
                             lang_cookie)
            self.assertEqual(
                self.client.cookies[settings.LANGUAGE_COOKIE].value,
                lang_cookie)
        else:
            self.assertEqual(response['Content-Language'], 'en')
            self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY),
                             None)
            self.assertEqual(
                self.client.cookies[settings.LANGUAGE_COOKIE].value, '')

    def test_process_response_no_user_noop(self):
        del self.request.user
        response = mock.Mock(spec=HttpResponse)

        result = self.middleware.process_response(self.request, response)

        self.assertIs(result, response)
        self.assertEqual(response.mock_calls, [])

    def test_preference_update_noop(self):
        self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'es'

        # No preference yet, should write to the database

        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), None)
        self.middleware.process_request(self.request)
        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'es')

        response = mock.Mock(spec=HttpResponse)

        with self.assertNumQueries(1):
            self.middleware.process_response(self.request, response)

        # Preference is the same as the cookie, shouldn't write to the database

        with self.assertNumQueries(3):
            self.middleware.process_request(self.request)

        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'es')

        response = mock.Mock(spec=HttpResponse)

        with self.assertNumQueries(1):
            self.middleware.process_response(self.request, response)

        # Cookie changed, should write to the database again

        self.request.COOKIES[settings.LANGUAGE_COOKIE] = 'en'
        self.middleware.process_request(self.request)
        self.assertEqual(get_user_preference(self.user, LANGUAGE_KEY), 'en')

        with self.assertNumQueries(1):
            self.middleware.process_response(self.request, response)

    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.is_request_from_mobile_app'
    )
    @mock.patch(
        'openedx.core.djangoapps.lang_pref.middleware.get_user_preference')
    def test_remove_lang_cookie_for_mobile_app(self, mock_get_user_preference,
                                               mock_is_mobile_request):
        """
        Test to verify language preference cookie removed for mobile app requests.
        """
        mock_get_user_preference.return_value = 'en'
        mock_is_mobile_request.return_value = False
        response = mock.Mock(spec=HttpResponse)

        response = self.middleware.process_response(self.request, response)
        response.delete_cookie.assert_not_called()
        response.set_cookie.assert_called()

        mock_is_mobile_request.return_value = True
        response = self.middleware.process_response(self.request, response)
        response.delete_cookie.assert_called()
示例#55
0
 def setUp(self):
     self.request = RequestFactory().get('/')
     middleware = SessionMiddleware()
     middleware.process_request(self.request)
     self.request.session.save()
def csdf(rf):
    """"""
    request = rf.get('/')
    middleware = SessionMiddleware(get_response_for_test)
    middleware.process_request(request)
    return CheckoutSessionData(request)
示例#57
0
 def add_session_to_request(self, request):
     middleware = SessionMiddleware()
     middleware.process_request(request)
     request.session.save()
示例#58
0
class AnnouncementCloseTestCase(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = get_user_model().objects.create_user(
            username="******",
            email="*****@*****.**",
            password="******",
        )
        self.middleware = SessionMiddleware()

    def test_get_request(self):
        for user in [self.user, AnonymousUser()]:
            request = self.factory.get(
                reverse("announcements:close-announcement"))
            self.middleware.process_request(request)
            with self.subTest(user=user):
                request.user = user
                response = close_announcement(request)
                self.assertEqual(response.status_code, 405)

    def test_post_no_id(self):
        request = self.factory.post(
            reverse("announcements:close-announcement"))
        self.middleware.process_request(request)
        request.user = AnonymousUser()
        response = close_announcement(request)
        self.assertEqual(response.status_code, 400)

    def test_post_id_string(self):
        request = self.factory.post(
            reverse("announcements:close-announcement"), {"id": "bla"})
        self.middleware.process_request(request)
        request.user = AnonymousUser()
        response = close_announcement(request)
        self.assertEqual(response.status_code, 400)

    def test_valid_request_anonymous(self):
        request = self.factory.post(
            reverse("announcements:close-announcement"), {"id": 3})
        self.middleware.process_request(request)
        request.user = AnonymousUser()
        response = close_announcement(request)

        self.assertEqual(response.status_code, 204)
        self.assertIn("closed_announcements", request.session)
        self.assertIn(3, request.session["closed_announcements"])
        self.assertTrue(request.session.modified)
        self.assertEqual(response.content, b"")

    def test_valid_request_logged_in(self):
        request = self.factory.post(
            reverse("announcements:close-announcement"), {"id": 3})
        self.middleware.process_request(request)
        request.user = self.user
        response = close_announcement(request)

        self.assertEqual(response.status_code, 204)
        self.assertIn("closed_announcements", request.session)
        self.assertIn(3, request.session["closed_announcements"])
        self.assertEqual(response.content, b"")

    def test_valid_alread_canceled(self):
        request = self.factory.post(
            reverse("announcements:close-announcement"), {"id": 3})
        self.middleware.process_request(request)
        request.session["closed_announcements"] = [3]
        request.user = AnonymousUser()
        response = close_announcement(request)

        self.assertEqual(response.status_code, 204)
        self.assertIn("closed_announcements", request.session)
        self.assertIn(3, request.session["closed_announcements"])
        self.assertEqual(len(request.session["closed_announcements"]), 1)
        self.assertTrue(request.session.modified)
        self.assertEqual(response.content, b"")
示例#59
0
def setup_request(request):
    middleware = SessionMiddleware()
    middleware.process_request(request)
    request.session.save()
    return request
示例#60
0
 def process_requests(req):
     middleware = SessionMiddleware()
     md = MessageMiddleware()
     middleware.process_request(req)
     md.process_request(req)