Example #1
0
 def test_put_request(self):
     middleware = DBRoutingMiddleware()
     request = Mock(spec=HttpRequest, method="PUT")
     request.session = {}
     output = middleware.process_request(request)
     self.assertIsNone(output)
     self.assertTrue(is_thread_readwrite())
    def _test_authorize_template(self, response_type="supported_grant", factory_ex=None, handler_ex=None):
        """This method provides a template method for testing handle_authorize method from oauth2 controller."""

        expected_response = Mock()

        client_facade = Mock()
        client_facade.session = Mock()

        request = Mock()
        request.params = {"response_type": response_type}

        request.models = Mock()
        request.models.Client = client_facade

        grant_handler = Mock()

        if not handler_ex:
            grant_handler.handle_grant = Mock(return_value=expected_response)
        else:
            grant_handler.handle_grant = Mock(side_effect=handler_ex)

        if not factory_ex:
            self._handlers_factory.get_handler = Mock(return_value=grant_handler)
        else:
            self._handlers_factory.get_handler = Mock(side_effect=factory_ex)

        response = self._oauth2_controller.handle_authorize(request)

        self.assertEqual(expected_response, response)

        self._handlers_factory.get_handler.assert_called_once_with("supported_grant", client_facade.session)
        grant_handler.handle_grant.assert_called_once_with(request)
Example #3
0
    def test_login_and_store_credentials_in_session(self):
        # only testing custom logic, which happens on POST
        # everything else is handled by django.contrib.auth
        mockrequest = Mock()
        mockrequest.method = "POST"

        def not_logged_in(rqst):
            rqst.user.is_authenticated.return_value = False

        def set_logged_in(rqst):
            rqst.user.is_authenticated.return_value = True
            rqst.POST.get.return_value = "TEST_PASSWORD"

        # failed login
        with patch("eulfedora.views.authviews.login", new=Mock(side_effect=not_logged_in)):
            mockrequest.session = dict()
            response = login_and_store_credentials_in_session(mockrequest)
            self.assert_(
                FEDORA_PASSWORD_SESSION_KEY not in mockrequest.session,
                "user password for fedora should not be stored in session on failed login",
            )

        # successful login
        with patch("eulfedora.views.authviews.login", new=Mock(side_effect=set_logged_in)):
            response = login_and_store_credentials_in_session(mockrequest)
            self.assert_(
                FEDORA_PASSWORD_SESSION_KEY in mockrequest.session,
                "user password for fedora should be stored in session on successful login",
            )
            # test password stored in the mock request
            pwd = mockrequest.POST.get()
            # encrypted password stored in session
            sessionpwd = mockrequest.session[FEDORA_PASSWORD_SESSION_KEY]
            self.assertNotEqual(pwd, sessionpwd, "password should not be stored in the session without encryption")
            self.assertEqual(pwd, cryptutil.decrypt(sessionpwd), "user password stored in session is encrypted")
Example #4
0
 def test_create_courseref_only_lti(self, mocked):
     """
     Test that only LTI is allowed.
     """
     request = Mock()
     request.session = {}
     res = create_courseref(request)
     self.assertEqual(res.content, "Only LTI allowed")
Example #5
0
 def test_get_request(self):
     # Get request uses replica DB if not pinned
     middleware = DBRoutingMiddleware()
     request = Mock(spec=HttpRequest, method="GET")
     request.session = {}
     output = middleware.process_request(request)
     self.assertIsNone(output)
     self.assertFalse(is_thread_readwrite())
Example #6
0
    def test_set_flavour_permanent(self):
        request = Mock()
        request.session = MagicMock()

        set_flavour("mobile", request=request)
        self.assertEqual(request.session.__setitem__.call_args, None)
        set_flavour("mobile", request=request, permanent=True)
        self.assertEqual(request.session.__setitem__.call_args, ((settings.FLAVOURS_SESSION_KEY, "mobile"), {}))
Example #7
0
 def test_get_request_pinned(self):
     # If session is pinned, use master DB
     middleware = DBRoutingMiddleware()
     request = Mock(spec=HttpRequest, method="GET")
     request.session = {PINNING_KEY: datetime.now() + timedelta(seconds=30)}
     output = middleware.process_request(request)
     self.assertIsNone(output)
     self.assertTrue(is_thread_readwrite())
Example #8
0
    def test_get_default_view_smartphone(self):

        request = Mock()
        request.META = {"HTTP_USER_AGENT": ""}
        request.session = {}
        with patch("wirecloud.platform.views.ua_parse") as ua_parse_mock:
            ua_parse_mock.return_value = Mock(is_mobile=True)
            self.assertEqual(get_default_view(request), "smartphone")
            self.assertEqual(request.session["default_mode"], "smartphone")
Example #9
0
    def test_mask(self):
        mw = MasqueradeMiddleware()

        request = Mock(spec=HttpRequest)
        request.session = {"mask_user": "generic"}
        request.user = User.objects.get(username="super")

        mw.process_request(request)

        self.assert_(request.user.is_masked == True)
        self.assert_(request.user == User.objects.get(username="generic"))
Example #10
0
    def test_unmask(self):
        mw = MasqueradeMiddleware()

        request = Mock(spec=HttpRequest)
        request.session = {}
        request.user = User.objects.get(username="super")

        mw.process_request(request)

        self.assert_(request.user.is_masked == False)
        self.assert_(request.user == User.objects.get(username="super"))
Example #11
0
    def setUp(self):
        self.patch_redis_pubsub = patch("redis.Redis.pubsub")
        self.mock_redis_pubsub = self.patch_redis_pubsub.start()
        self.redis = Mock(spec=["listen", "subscribe"])
        self.redis.listen.return_value = [{"type": "message", "data": '"abcd"'}]
        self.mock_redis_pubsub.return_value = self.redis

        socket = Mock()
        socket.session = {"rooms": Mock()}
        self.environ = {"socketio": socket}
        self.ns_name = "/event/updates"
        self.request = Mock()
Example #12
0
    def test_update_session_lang_not_user_preference(self):

        request = Mock()
        request.session = {}

        user = Mock()
        with self.settings(DEFAULT_LANGUAGE="invented"):
            with patch("wirecloud.platform.preferences.models.PlatformPreference") as platform_preference_mock:
                platform_preference_mock.objects.filter.return_value = []
                update_session_lang(request, user)

        self.assertEqual(request.session[LANGUAGE_SESSION_KEY], "invented")
Example #13
0
 def test_post_request_without_write(self):
     middleware = DBRoutingMiddleware()
     request = Mock(spec=HttpRequest, method="POST")
     request.session = {}
     output = middleware.process_request(request)
     self.assertIsNone(output)
     self.assertTrue(is_thread_readwrite())
     response = Mock()
     output = middleware.process_response(request, response)
     self.assertEqual(output, response)
     # No write - did not pin
     self.assertNotIn(PINNING_KEY, request.session)
Example #14
0
    def test_transfer_error(self, mock_vofile):
        vofile = MagicMock()
        mock_vofile.return_value = vofile

        vospace_url = "https://somevospace.server/vospace"
        session = Mock()
        session.get.side_effect = [Mock(content="COMPLETED")]
        conn = Mock(spec=Connection)
        conn.session = session

        test_client = Client()

        # use the mocked connection instead of the real one
        test_client.conn = conn

        # job successfully completed
        vofile.read.side_effect = ["QUEUED", "COMPLETED"]
        self.assertFalse(test_client.get_transfer_error(vospace_url + "/results/transferDetails", "vos://vospace"))
        session.get.assert_called_once_with(vospace_url + "/phase", allow_redirects=False)

        # job suspended
        session.reset_mock()
        session.get.side_effect = [Mock(content="COMPLETED")]
        vofile.read.side_effect = ["QUEUED", "SUSPENDED"]
        with self.assertRaises(OSError):
            test_client.get_transfer_error(vospace_url + "/results/transferDetails", "vos://vospace")
        # check arguments for session.get calls
        self.assertEquals([call(vospace_url + "/phase", allow_redirects=False)], session.get.call_args_list)

        # job encountered an internal error
        session.reset_mock()
        vofile.read.side_effect = Mock(side_effect=["QUEUED", "ERROR"])
        session.get.side_effect = [Mock(content="COMPLETED"), Mock(content="InternalFault")]
        with self.assertRaises(OSError):
            test_client.get_transfer_error(vospace_url + "/results/transferDetails", "vos://vospace")
        self.assertEquals(
            [call(vospace_url + "/phase", allow_redirects=False), call(vospace_url + "/error")],
            session.get.call_args_list,
        )

        # job encountered an unsupported link error
        session.reset_mock()
        link_file = "testlink.fits"
        vofile.read.side_effect = Mock(side_effect=["QUEUED", "ERROR"])
        session.get.side_effect = [Mock(content="COMPLETED"), Mock(content="Unsupported link target: " + link_file)]
        self.assertEquals(
            link_file, test_client.get_transfer_error(vospace_url + "/results/transferDetails", "vos://vospace")
        )
        self.assertEquals(
            [call(vospace_url + "/phase", allow_redirects=False), call(vospace_url + "/error")],
            session.get.call_args_list,
        )
Example #15
0
 def test_post_request_with_write(self):
     middleware = DBRoutingMiddleware()
     request = Mock(spec=HttpRequest, method="POST")
     request.session = {}
     output = middleware.process_request(request)
     self.assertIsNone(output)
     self.assertTrue(is_thread_readwrite())
     set_db_written_flag()
     response = Mock()
     output = middleware.process_response(request, response)
     self.assertEqual(output, response)
     # Db was written, so pin
     self.assertTrue(request.session[PINNING_KEY] > datetime.now())
Example #16
0
    def test_update_session_lang_invalid_user_preference(self):

        request = Mock()
        request.session = {LANGUAGE_SESSION_KEY: "es"}

        user = Mock()
        with self.settings(DEFAULT_LANGUAGE="invented", LANGUAGES=(("es", "Spanish"),)):
            with patch("wirecloud.platform.preferences.models.PlatformPreference") as platform_preference_mock:
                lang_pref_mock = Mock()
                lang_pref_mock.value = "invalid"
                platform_preference_mock.objects.filter.return_value = [lang_pref_mock]
                update_session_lang(request, user)

        self.assertEqual(request.session[LANGUAGE_SESSION_KEY], "invented")
Example #17
0
    def test_update_session_lang_default_browser(self):

        request = Mock()
        request.session = {}

        user = Mock()
        with self.settings(DEFAULT_LANGUAGE="browser", LANGUAGES=(("en", "English"),)):
            with patch("wirecloud.platform.preferences.models.PlatformPreference") as platform_preference_mock:
                lang_pref_mock = Mock()
                lang_pref_mock.value = "default"
                platform_preference_mock.objects.filter.return_value = [lang_pref_mock]
                update_session_lang(request, user)

        self.assertNotIn(LANGUAGE_SESSION_KEY, request.session)
Example #18
0
 def test_create_courseref_existence(self, context_id, langing_page, mocked):
     """
     Test for existence/non-existence of CourseRef.
     """
     _id = self.course.id if context_id == "1" else self.course.id + 1
     lti_post = {
         "context_id": context_id,
         "context_title": "test title",
         "tool_consumer_instance_guid": "test.dot.com",
         "roles": "Instructor",
     }
     request = Mock()
     request.user = self.user
     request.session = {"LTI_POST": lti_post, "is_valid": True}
     res = create_courseref(request)
     self.assertEqual(res.url, reverse(langing_page, args=(_id,)))
Example #19
0
 def test_change_plan_form(self):
     request = Mock()
     request.META = {}
     request.session = DummySession()
     user = get_user_model().objects.create_user(username="patrick")
     user.set_password("eldarion")
     user.save()
     customer = CustomerProxy.objects.create(stripe_id="cus_1", user=user)
     plan = PlanProxy.objects.create(amount=10, currency="usd", interval="monthly", interval_count=1, name="Pro")
     SubscriptionProxy.objects.create(
         customer=customer, plan=plan, quantity=1, start=timezone.now(), status="active", cancel_at_period_end=False
     )
     user = authenticate(username="patrick", password="eldarion")
     login(request, user)
     context = {"request": request}
     change_plan_form(context)
     self.assertTrue("form" in context)
Example #20
0
 def test_default(self):
     request = Mock(spec_set=["GET", "session"])
     request.GET = {}
     request.session = {}
     context = ProfilingView()._create_context(request)
     self.assertDictContainsSubset(
         {
             "show": ProfilingView.default_show,
             "order_by": ProfilingView.defualt_order_by,
             "options_show": ProfilingView.show,
             "options_order_by": ProfilingView.order_by,
             "options_func_names": ProfilingView()._get_function_names(),
         },
         context,
     )
     self.assertNotIn("path", context)
     self.assertIn("results", context)
Example #21
0
    def setUp(self):
        from mock import Mock

        mock_request = Mock()
        mock_request.GET = {}
        mock_request.session = {"twitter_request_token_key": "key", "twitter_request_token_secret": "secret"}
        self.request = mock_request
        self.request.route_url.return_value = "/"
        # Setup mock oauth handler and tweepy client.
        self.mock_handler_factory = Mock()
        self.mock_handler = Mock()
        self.mock_handler.access_token.key = "key"
        self.mock_handler.access_token.secret = "secret"
        self.mock_handler_factory.return_value = self.mock_handler
        self.mock_api_factory = Mock()
        self.mock_client = Mock()
        self.mock_client.last_response.getheader.return_value = "read"
        self.mock_api_factory.return_value = self.mock_client
Example #22
0
 def test_default(self):
     request = Mock(spec_set=["GET", "session"])
     request.session = {}
     request.GET = {}
     context = RequestsView()._create_context(request)
     self.assertDictContainsSubset(
         {
             "show": RequestsView.default_show,
             "order_by": RequestsView.default_order_by,
             "options_show": RequestsView.show,
             "options_order_by": RequestsView().options_order_by,
             "options_order_dir": RequestsView().options_order_dir,
             "options_paths": RequestsView()._get_paths(),
         },
         context,
     )
     self.assertNotIn("path", context)
     self.assertIn("results", context)
Example #23
0
 def test_get(self):
     request = Mock(spec_set=["GET", "session"])
     request.session = {}
     show = 10
     path = "/path/to/somewhere/"
     order_by = "Path"
     request.GET = {"show": show, "path": path, "order_by": order_by}
     context = RequestsView()._create_context(request)
     self.assertDictContainsSubset(
         {
             "show": show,
             "order_by": order_by,
             "path": path,
             "options_show": RequestsView.show,
             "options_order_by": RequestsView.order_by,
             "options_paths": RequestsView()._get_paths(),
         },
         context,
     )
     self.assertIn("results", context)
Example #24
0
    def test_another_user_logged_out(self, get, now):

        # user requests email change
        user = Mock()
        token_object = Mock()
        token_object.token = "sometokencontent"
        token_object.user = user
        get.return_value = token_object

        # another user is logged in
        another_user = Mock()
        request = Mock()
        request.user = another_user
        request.session = SessionMock()

        # first user clicks link in his email
        result = change_email(request, token_object.token)
        self.assertEquals(result.status_code, 302)
        get.assert_called_once_with(token=token_object.token, valid_until__gte=now())
        self.assertFalse(request.user.is_authenticated())
        token_object.delete.assert_not_called()
 def test_change_plan_form(self):
     request = Mock()
     request.session = DummySession()
     user = get_user_model().objects.create_user(username="patrick")
     user.set_password("eldarion")
     user.save()
     customer = Customer.objects.create(stripe_id="cus_1", user=user)
     CurrentSubscription.objects.create(
         customer=customer,
         plan="pro",
         quantity=1,
         start=timezone.now(),
         status="active",
         cancel_at_period_end=False,
         amount=decimal.Decimal("19.99"),
     )
     user = authenticate(username="patrick", password="eldarion")
     login(request, user)
     context = {"request": request}
     change_plan_form(context)
     self.assertTrue("form" in context)
Example #26
0
 def test_get(self):
     request = Mock(spec_set=["GET", "session"])
     request.session = {}
     show = 10
     func_name = "func_name"
     name = "name"
     order_by = "Time"
     request.GET = {"show": show, "func_name": func_name, "name": name, "order_by": order_by}
     context = ProfilingView()._create_context(request)
     self.assertDictContainsSubset(
         {
             "show": show,
             "order_by": order_by,
             "func_name": func_name,
             "name": name,
             "options_show": ProfilingView.show,
             "options_order_by": ProfilingView.order_by,
             "options_func_names": ProfilingView()._get_function_names(),
         },
         context,
     )
     self.assertIn("results", context)
    def _mock_authenticate_dependencies(self, token, user, return_url):
        """This method mocks authenticate dependencies and returns them as a tuple object."""

        if return_url:
            return_url_base = return_url

            if return_url_base.find("?") > -1:
                return_url_base = return_url_base[: return_url_base.find("?")]

        clienturl_facade = Mock()

        if return_url:
            clienturl_facade.get_records_paged = Mock(return_value=[return_url_base])
        clienturl_facade.session = Mock()

        request = Mock()
        request.params = {
            "username": user.username,
            "password": user.password,
            self._idp_controller.REDIRECT_PARAM: return_url,
        }
        request.models = Mock()
        request.models.ClientReturnUrl = clienturl_facade
        request.redirect = lambda destination: RedirectResponse(destination)

        user_repo = Mock()
        user_repo.load_by_username = Mock(return_value=user)
        user_repo_cls = Mock(return_value=user_repo)

        self._hasher.hash_password = Mock(return_value="12345")

        tokens_service = Mock()
        tokens_service_cls = Mock(return_value=tokens_service)

        tokens_service.generate = Mock(return_value=token)
        tokens_service.encrypt = Mock(return_value="123")

        return (request, user_repo_cls, user_repo, tokens_service_cls, tokens_service, clienturl_facade)
Example #28
0
    def test_set_flavour_with_session_backend(self):
        original_FLAVOURS_STORAGE_BACKEND = settings.FLAVOURS_STORAGE_BACKEND
        try:
            settings.FLAVOURS_STORAGE_BACKEND = "session"
            request = Mock()
            request.session = {}
            set_flavour("mobile", request=request)
            self.assertEqual(request.session, {})
            set_flavour("mobile", request=request, permanent=True)
            self.assertEqual(request.session, {settings.FLAVOURS_SESSION_KEY: u"mobile"})
            self.assertEqual(get_flavour(request), "mobile")

            response = self.client.get("/")
            self.assertFalse("sessionid" in response.cookies)
            response = self.client.get("/", {settings.FLAVOURS_GET_PARAMETER: "mobile"})
            self.assertTrue("sessionid" in response.cookies)
            sessionid = response.cookies["sessionid"].value
            session = Session.objects.get(session_key=sessionid)
            session_data = session.get_decoded()
            self.assertTrue(settings.FLAVOURS_SESSION_KEY in session_data)
            self.assertEqual(session_data[settings.FLAVOURS_SESSION_KEY], "mobile")
        finally:
            settings.FLAVOURS_STORAGE_BACKEND = original_FLAVOURS_STORAGE_BACKEND
def get_mock_request():
    r = Mock()
    r.session = Mock()
    r.session.session_key = "287384"
    r.build_absolute_uri = lambda x: x
    return r
def setup_module(mod):
    global mw
    global request
    mw = OauthAdminSessionMiddleware()
    request = Mock()
    request.session = {}