浏览代码

[beeswax] Update session tests and allow superuser to close any session

Jenny Kim 10 年之前
父节点
当前提交
72b7739d9c
共有 4 个文件被更改,包括 113 次插入51 次删除
  1. 4 1
      apps/beeswax/src/beeswax/api.py
  2. 2 2
      apps/beeswax/src/beeswax/models.py
  3. 84 44
      apps/beeswax/src/beeswax/tests.py
  4. 23 4
      apps/impala/src/impala/tests.py

+ 4 - 1
apps/beeswax/src/beeswax/api.py

@@ -839,7 +839,10 @@ def close_session(request, session_id):
   response = {'status': -1, 'message': ''}
 
   try:
-    session = Session.objects.get(id=session_id, owner=request.user, application=query_server['server_name'])
+    filters = {'id': session_id, 'application': query_server['server_name']}
+    if not request.user.is_superuser:
+      filters['owner'] = request.user
+    session = Session.objects.get(**filters)
   except Session.DoesNotExist:
     response['message'] = _('Session does not exist or you do not have permissions to close the session.')
 

+ 2 - 2
apps/beeswax/src/beeswax/models.py

@@ -386,10 +386,10 @@ class SavedQuery(models.Model):
 
 class SessionManager(models.Manager):
 
-  def get_session(self, user, application='beeswax', open_sessions=True):
+  def get_session(self, user, application='beeswax', filter_open=True):
     try:
       q = self.filter(owner=user, application=application)
-      if open_sessions:
+      if filter_open:
         q = q.filter(status_code=0)
       return q.latest("last_used")
     except Session.DoesNotExist, e:

+ 84 - 44
apps/beeswax/src/beeswax/tests.py

@@ -252,6 +252,49 @@ for x in sys.stdin:
     assert_equal(257, ''.join(response.streaming_content).count("\n"))
 
 
+  def test_api_get_session(self):
+    session = None
+    try:
+      # Create open session
+      session = self.db.open_session(self.user)
+
+      resp = self.client.get(reverse("beeswax:api_get_session"))
+      data = json.loads(resp.content)
+      assert_true('properties' in data, data)
+      assert_true('session' in data, data)
+      assert_true('id' in data['session'], data['session'])
+    finally:
+      if session is not None:
+        try:
+          self.db.close_session(session)
+        except Exception:
+          pass
+
+
+  def test_api_close_session(self):
+    session = None
+    try:
+      # Create open session
+      session = self.db.open_session(self.user)
+
+      resp = self.client.post(reverse("beeswax:api_close_session", kwargs={'session_id': session.id}))
+      data = json.loads(resp.content)
+      assert_equal(0, data['status'])
+      assert_true('session' in data)
+      assert_equal(4, data['session']['status'])
+
+      # Closed sessions will return error response
+      resp = self.client.post(reverse("beeswax:api_close_session", kwargs={'session_id': session.id}))
+      data = json.loads(resp.content)
+      assert_equal(-1, data['status'])
+    finally:
+      if session is not None:
+        try:
+          self.db.close_session(session)
+        except Exception:
+          pass
+
+
   def test_result_escaping(self):
     # Check for XSS and NULL display
     QUERY = """
@@ -774,6 +817,7 @@ for x in sys.stdin:
 
     assert_equal(sheet_data, csv_data)
 
+
   def test_data_upload(self):
     hql = 'SELECT * FROM `%(db)s`.`test`' % {'db': self.db_name}
     query = hql_query(hql)
@@ -1244,6 +1288,7 @@ for x in sys.stdin:
     flat_rows = sum(rows, [])
     assert_true("2012-01-01 10:11:30.0" in flat_rows, flat_rows)
 
+
   def test_partitioned_create_table(self):
     # Make sure we get a form
     resp = self.client.get("/beeswax/create/create_table/%s" % self.db_name)
@@ -2002,6 +2047,7 @@ def test_history_page():
       query_type=HQL
   )
 
+
   def do_view(param, n=1):
     resp = client.get('/beeswax/query_history?' + param)
     if n == 0:
@@ -2055,6 +2101,7 @@ def teststrip_trailing_semicolon():
   # No semicolons
   assert_equal("foo", strip_trailing_semicolon("foo"))
 
+
 def test_hadoop_extraction():
   sample_log = """
 Starting Job = job_201003191517_0002, Tracking URL = http://localhost:50030/jobdetails.jsp?jobid=job_201003191517_0002
@@ -2079,6 +2126,7 @@ Starting Job = job_201003191517_0003, Tracking URL = http://localhost:50030/jobd
       ["job_1402269517321_0003"],
       beeswax.views._parse_out_hadoop_jobs(sample_log_no_direct_url))
 
+
 def test_hive_site():
   tmpdir = tempfile.mkdtemp()
   saved = None
@@ -2243,16 +2291,6 @@ ALTER TABLE alltypes ADD IF NOT EXISTS PARTITION(year=2009, month=2);"""
               hql_query(query).statements, hql_query(query).statements)
 
 
-def test_api_get_session():
-  client = make_logged_in_client(is_superuser=False)
-  grant_access("test", "test", "beeswax")
-
-  resp = client.get(reverse("beeswax:api_get_session"))
-
-  data = json.loads(resp.content)
-  assert_true('properties' in data)
-
-
 class MockHiveServerTable(HiveServerTable):
 
   def __init__(self, describe=None):
@@ -2309,6 +2347,7 @@ class TestHiveServer2API():
     value = PartitionValueCompatible(['month=2011-07/dt=2011-07-01/hr=12'], table)
     assert_equal(['2011-07', '2011-07-01', '12'], value.values)
 
+
   def test_hiveserver_table(self):
     table = MockHiveServerTable()
 
@@ -2435,6 +2474,7 @@ class TestHiveServer2API():
                   None, 1, 1, 1, None, None, None, 1, None, 1, None, 1, None, None, 1, None, None, 1, 1, None, None, None, None, None, None, 1, None, None, None],
                  HiveServerTColumnValue2.set_nulls(data, nulls))
 
+
   def test_column_detect_if_values_nulls(self):
     data = [1, 2, 3]
 
@@ -2838,40 +2878,40 @@ class MockClient():
     self.open_session_args = args
 
 
-#def test_hive_server2_open_session():
-#  make_logged_in_client()
-#  user = User.objects.get(username='test')
-#
-#  query_server = get_query_server_config()
-#
-#  db_client = HiveServerClient(query_server, user)
-#  mock_hs2_client = MockClient()
-#  setattr(db_client, '_client', mock_hs2_client)
-#
-#  # Regular session
-#  finish = desktop_conf.LDAP_PASSWORD.set_for_testing('')
-#  try:
-#    db_client.open_session(user)
-#  except:
-#    pass
-#  finally:
-#    finish()
-#    req = mock_hs2_client.open_session_args
-#    assert_equal('test', req.username)
-#    assert_equal(None, req.password)
-#    assert_equal('test', req.configuration['hive.server2.proxy.user'])
-#
-#  # LDAP credentials
-#  finish = desktop_conf.LDAP_PASSWORD.set_for_testing('I_love_Hue')
-#  try:
-#    db_client.open_session(user)
-#  except:
-#    pass
-#  finally:
-#    finish()
-#    req = mock_hs2_client.open_session_args
-#    assert_equal('test', req.username) # Same as kerberos, real username is picked from Thrift authentication, this one does not matter
-#    assert_equal(None, req.password)
+  #def test_hive_server2_open_session():
+  #  make_logged_in_client()
+  #  user = User.objects.get(username='test')
+  #
+  #  query_server = get_query_server_config()
+  #
+  #  db_client = HiveServerClient(query_server, user)
+  #  mock_hs2_client = MockClient()
+  #  setattr(db_client, '_client', mock_hs2_client)
+  #
+  #  # Regular session
+  #  finish = desktop_conf.LDAP_PASSWORD.set_for_testing('')
+  #  try:
+  #    db_client.open_session(user)
+  #  except:
+  #    pass
+  #  finally:
+  #    finish()
+  #    req = mock_hs2_client.open_session_args
+  #    assert_equal('test', req.username)
+  #    assert_equal(None, req.password)
+  #    assert_equal('test', req.configuration['hive.server2.proxy.user'])
+  #
+  #  # LDAP credentials
+  #  finish = desktop_conf.LDAP_PASSWORD.set_for_testing('I_love_Hue')
+  #  try:
+  #    db_client.open_session(user)
+  #  except:
+  #    pass
+  #  finally:
+  #    finish()
+  #    req = mock_hs2_client.open_session_args
+  #    assert_equal('test', req.username) # Same as kerberos, real username is picked from Thrift authentication, this one does not matter
+  #    assert_equal(None, req.password)
 
 
 def test_metastore_security():

+ 23 - 4
apps/impala/src/impala/tests.py

@@ -48,6 +48,7 @@ LOG = logging.getLogger(__name__)
 
 
 class MockDbms:
+
   def get_databases(self):
     return ['db1', 'db2']
 
@@ -56,6 +57,7 @@ class MockDbms:
 
 
 class TestMockedImpala:
+
   def setUp(self):
     self.client = make_logged_in_client()
 
@@ -149,6 +151,7 @@ class TestImpalaIntegration:
     content = json.loads(resp.content)
     assert_true(content['status'] == 0, resp.content)
 
+
   @classmethod
   def teardown_class(cls):
     # We need to drop tables before dropping the database
@@ -168,6 +171,7 @@ class TestImpalaIntegration:
     for f in cls.finish:
       f()
 
+
   def test_basic_flow(self):
     dbs = self.db.get_databases()
     assert_true('_impala_builtins' in dbs, dbs)
@@ -217,6 +221,7 @@ class TestImpalaIntegration:
     assert_true('MERGING-EXCHANGE' in json_response['explanation'], json_response)
     assert_true('SCAN HDFS' in json_response['explanation'], json_response)
 
+
   def test_get_table_sample(self):
     client = make_logged_in_client()
 
@@ -226,11 +231,25 @@ class TestImpalaIntegration:
     assert_equal([u'row_num', u'id_str', u'text'], data['headers'], data)
     assert_true(len(data['rows']), data)
 
+
   def test_get_session(self):
-    resp = self.client.get(reverse("impala:api_get_session"))
-    data = json.loads(resp.content)
-    assert_true('properties' in data)
-    assert_true(data['properties'].get('http_addr'))
+    session = None
+    try:
+      # Create open session
+      session = self.db.open_session(self.user)
+
+      resp = self.client.get(reverse("impala:api_get_session"))
+      data = json.loads(resp.content)
+      assert_true('properties' in data)
+      assert_true(data['properties'].get('http_addr'))
+      assert_true('session' in data, data)
+      assert_true('id' in data['session'], data['session'])
+    finally:
+      if session is not None:
+        try:
+          self.db.close_session(session)
+        except Exception:
+          pass
 
 
   def test_invalidate_tables(self):