def setUp(self): load_test_data(self) self.mox = mox.Mox() self.factory = RequestFactoryWithMessages() self.context = {'authorized_tenants': self.tenants.list()} def fake_conn_request(*args, **kwargs): raise Exception("An external URI request tried to escape through " "an httplib2 client. Args: %s, kwargs: %s" % (args, kwargs)) self._real_conn_request = httplib2.Http._conn_request httplib2.Http._conn_request = fake_conn_request self._real_horizon_context_processor = context_processors.horizon context_processors.horizon = lambda request: self.context self._real_get_user = utils.get_user tenants = self.context['authorized_tenants'] self.setActiveUser(id=self.user.id, token=self.token, username=self.user.name, tenant_id=self.tenant.id, service_catalog=self.service_catalog, authorized_tenants=tenants) self.request = http.HttpRequest() self.request.session = self.client._session() self.request.session['token'] = self.token.id middleware.HorizonMiddleware().process_request(self.request) AuthenticationMiddleware().process_request(self.request) os.environ["HORIZON_TEST_RUN"] = "True"
def setUp(self): self.mox = mox.Mox() self.factory = RequestFactoryWithMessages() def fake_conn_request(*args, **kwargs): raise Exception("An external URI request tried to escape through " "an httplib2 client. Args: %s, kwargs: %s" % (args, kwargs)) self._real_conn_request = httplib2.Http._conn_request httplib2.Http._conn_request = fake_conn_request self._real_horizon_context_processor = context_processors.horizon context_processors.horizon = lambda request: self.TEST_CONTEXT self._real_get_user_from_request = users.get_user_from_request tenants = self.TEST_CONTEXT['authorized_tenants'] self.setActiveUser(token=self.TEST_TOKEN, username=self.TEST_USER, tenant_id=self.TEST_TENANT, service_catalog=self.TEST_SERVICE_CATALOG, authorized_tenants=tenants) self.request = http.HttpRequest() self.request.session = self.client._session() middleware.HorizonMiddleware().process_request(self.request)
def test_redirect_login_fail_to_login(self): url = settings.LOGIN_URL request = self.factory.post(url) mw = middleware.HorizonMiddleware() resp = mw.process_exception(request, exceptions.NotAuthorized()) resp.client = self.client self.assertRedirects(resp, url)
def setUp(self): super(TestCase, self).setUp() self.mox = mox.Mox() self._setup_test_data() self._setup_factory() self._setup_user() self._setup_request() middleware.HorizonMiddleware().process_request(self.request) AuthenticationMiddleware().process_request(self.request) os.environ["HORIZON_TEST_RUN"] = "True"
def test_redirect_login_fail_to_login(self): url = settings.LOGIN_URL request = self.factory.post(url) self.get_response.return_value = request mw = middleware.HorizonMiddleware(self.get_response) resp = mw.process_exception(request, exceptions.NotAuthenticated()) resp.client = self.client self.assertRedirects(resp, settings.TESTSERVER + url)
def test_tab_302_exception(self): TabWithTableView.tab_group_class.tabs.append(RedirectExceptionTab) view = TabWithTableView.as_view() req = self.factory.get("/") mw = middleware.HorizonMiddleware('dummy_get_response') try: resp = view(req) except Exception as e: resp = mw.process_exception(req, e) resp.client = self.client self.assertRedirects(resp, RedirectExceptionTab.url)
def setUp(self): self.mox = mox.Mox() self.factory = RequestFactoryWithMessages() self.user = User.objects.create_user(username='******', password='******') self.assertTrue(self.client.login(username="******", password="******")) self.request = http.HttpRequest() self.request.session = self.client._session() middleware.HorizonMiddleware().process_request(self.request) AuthenticationMiddleware().process_request(self.request) os.environ["HORIZON_TEST_RUN"] = "True"
def test_middleware_header(self): req = self.request string = _("Giant ants are attacking San Francisco!") expected = ["error", force_unicode(string), ""] self.assertTrue("async_messages" in req.horizon) self.assertItemsEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' messages.error(req, string) self.assertItemsEqual(req.horizon['async_messages'], [expected]) res = http.HttpResponse() res = middleware.HorizonMiddleware().process_response(req, res) self.assertEqual(res['X-Horizon-Messages'], json.dumps([expected]))
def test_safe_message(self): req = self.request string = mark_safe(_("We are now safe from ants! Go <a>here</a>!")) expected = ["error", force_unicode(string), " safe"] self.assertTrue("async_messages" in req.horizon) self.assertItemsEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' messages.error(req, string) self.assertItemsEqual(req.horizon['async_messages'], [expected]) res = http.HttpResponse() res = middleware.HorizonMiddleware().process_response(req, res) self.assertEqual(res['X-Horizon-Messages'], json.dumps([expected]))
def test_redirect_login_fail_to_login(self): url = settings.LOGIN_URL request = self.factory.post(url) mw = middleware.HorizonMiddleware() resp = mw.process_exception(request, exceptions.NotAuthenticated()) resp.client = self.client if django.VERSION >= (1, 9): self.assertRedirects(resp, settings.TESTSERVER + url) else: self.assertRedirects(resp, url)
def test_session_timeout(self): requested_url = '/project/instances/' request = self.factory.get(requested_url) try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 request.session['last_activity'] = int(time.time()) - (timeout + 10) mw = middleware.HorizonMiddleware() resp = mw.process_request(request) self.assertEqual(302, resp.status_code) self.assertEqual(requested_url, resp.get('Location'))
def test_middleware_header(self): req = self.request string = "Giant ants are attacking San Francisco!" expected = ["error", force_text(string), ""] self.assertIn("async_messages", req.horizon) self.assertCountEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' messages.error(req, string) self.assertCountEqual(req.horizon['async_messages'], [expected]) res = http.HttpResponse() res = middleware.HorizonMiddleware('dummy_get_response') \ ._process_response(req, res) self.assertEqual(json.dumps([expected]), res['X-Horizon-Messages'])
def test_error_message(self): req = self.request string = mark_safe("We are now safe from ants! Go <a>here</a>!") expected = ["error", force_text(string), " safe"] self.assertIn("async_messages", req.horizon) self.assertCountEqual(req.horizon['async_messages'], []) req.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' messages.error(req, string) self.assertCountEqual(req.horizon['async_messages'], [expected]) res = http.HttpResponse() res = middleware.HorizonMiddleware('dummy_get_response') \ ._process_response(req, res) self.assertEqual(json.dumps([expected]), res['X-Horizon-Messages'])
def setUp(self): super().setUp() self._setup_test_data() self._setup_factory() self._setup_user() self._setup_request() # A dummy get_response function (which is not callable) is passed # because middlewares below are used only to populate request attrs. middleware.HorizonMiddleware('dummy_get_response') \ ._process_request(self.request) AuthenticationMiddleware('dummy_get_response') \ .process_request(self.request) os.environ["HORIZON_TEST_RUN"] = "True"
def setUp(self): self.mox = mox.Mox() self._real_horizon_context_processor = context_processors.horizon context_processors.horizon = lambda request: self.TEST_CONTEXT self._real_get_user_from_request = users.get_user_from_request self.setActiveUser(token=self.TEST_TOKEN, username=self.TEST_USER, tenant_id=self.TEST_TENANT, service_catalog=self.TEST_SERVICE_CATALOG) self.request = http.HttpRequest() middleware.HorizonMiddleware().process_request(self.request)
def test_redirect_session_timeout(self): requested_url = '/project/instances/' response_url = '%s?next=%s' % (settings.LOGOUT_URL, requested_url) request = self.factory.get(requested_url) try: timeout = settings.SESSION_TIMEOUT except AttributeError: timeout = 1800 request.session['last_activity'] =\ datetime.datetime.now() - datetime.timedelta(seconds=timeout + 10) mw = middleware.HorizonMiddleware() resp = mw.process_request(request) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.get('Location'), response_url)
def test_authorized_tenants(self): tenant_list = self.TEST_CONTEXT['authorized_tenants'] self.request.user.authorized_tenants = None # Reset from setUp self.mox.StubOutWithMock(api, 'tenant_list_for_token') api.tenant_list_for_token(IsA(http.HttpRequest), self.TEST_TOKEN, endpoint_type='internalURL') \ .AndReturn(tenant_list) self.mox.ReplayAll() middleware.HorizonMiddleware().process_request(self.request) context = context_processors.horizon(self.request) self.assertEqual(len(context['authorized_tenants']), 1) tenant = context['authorized_tenants'].pop() self.assertEqual(tenant['id'], self.TEST_TENANT)
def test_timezone_awareness(self): url = settings.LOGIN_REDIRECT_URL mw = middleware.HorizonMiddleware() request = self.factory.get(url) request.session['django_timezone'] = 'America/Chicago' mw.process_request(request) self.assertEqual( timezone.get_current_timezone_name(), 'America/Chicago') request.session['django_timezone'] = 'Europe/Paris' mw.process_request(request) self.assertEqual(timezone.get_current_timezone_name(), 'Europe/Paris') request.session['django_timezone'] = 'UTC' mw.process_request(request) self.assertEqual(timezone.get_current_timezone_name(), 'UTC')
def test_process_response_redirect_on_ajax_request(self): url = settings.LOGIN_URL mw = middleware.HorizonMiddleware() request = self.factory.post(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest') request.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest' request.horizon = {'async_messages': [('error', 'error_msg', 'extra_tag')]} response = HttpResponseRedirect(url) response.client = self.client resp = mw.process_response(request, response) self.assertEqual(200, resp.status_code) self.assertEqual(url, resp['X-Horizon-Location'])
def test_no_refresh_session_expiry(self): url = settings.LOGIN_REDIRECT_URL mw = middleware.HorizonMiddleware(self.get_response) request = self.factory.get(url) now = datetime.datetime.now(pytz.utc) token_expiry = now + datetime.timedelta(seconds=1800) request.user.token = mock.Mock(expires=token_expiry) session_expiry_before = now + datetime.timedelta(seconds=300) request.session.set_expiry(session_expiry_before) mw._process_request(request) session_expiry_after = request.session.get_expiry_date() # Check if session_expiry has been updated. self.assertEqual(session_expiry_after, session_expiry_before)
def setUp(self): super(TestCase, self).setUp() if self.use_mox: LOG.warning("'use_mox' will be dropped at the beginning of " "'Stein' release. If you still depend on mox, " "you must prepare mox environment in your test case.") self.mox = mox.Mox() self._setup_test_data() self._setup_factory() self._setup_user() self._setup_request() # A dummy get_response function (which is not callable) is passed # because middlewares below are used only to populate request attrs. middleware.HorizonMiddleware('dummy_get_response') \ .process_request(self.request) AuthenticationMiddleware('dummy_get_response') \ .process_request(self.request) os.environ["HORIZON_TEST_RUN"] = "True"
def test_refresh_session_expiry_near_token_expiry(self): url = settings.LOGIN_REDIRECT_URL mw = middleware.HorizonMiddleware(self.get_response) request = self.factory.get(url) now = datetime.datetime.now(pytz.utc) token_expiry = now + datetime.timedelta(seconds=10) request.user.token = mock.Mock(expires=token_expiry) mw._process_request(request) session_expiry_after = request.session.get_expiry_date() # Check if session_expiry_after is around token_expiry. # We set some margin to avoid accidental test failure. self.assertGreater(session_expiry_after, token_expiry - datetime.timedelta(seconds=3)) self.assertLess(session_expiry_after, token_expiry + datetime.timedelta(seconds=3))
def test_authorized_tenants(self): tenant_list = self.context['authorized_tenants'] self.request.user.authorized_tenants = None # Reset from setUp self.mox.StubOutWithMock(api, 'tenant_list_for_token') api.tenant_list_for_token(IsA(http.HttpRequest), self.token.id) \ .AndReturn(tenant_list) self.mox.ReplayAll() middleware.HorizonMiddleware().process_request(self.request) # Without dashboard that has "supports_tenants = True" context = context_processors.horizon(self.request) self.assertEqual(len(context['authorized_tenants']), 0) # With dashboard that has "supports_tenants = True" class ProjectDash(Dashboard): supports_tenants = True self.request.horizon['dashboard'] = ProjectDash self.assertTrue(self.request.user.is_authenticated()) context = context_processors.horizon(self.request) self.assertItemsEqual(context['authorized_tenants'], tenant_list)