You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by ta...@apache.org on 2019/04/30 15:36:04 UTC
[impala] 06/07: IMPALA-7290: part 1: clean up shell tests
This is an automated email from the ASF dual-hosted git repository.
tarmstrong pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git
commit 0a9ea803d2ed05135d1538dadf4b09ab6ad58e72
Author: Tim Armstrong <ta...@cloudera.com>
AuthorDate: Fri Mar 22 11:40:08 2019 -0700
IMPALA-7290: part 1: clean up shell tests
This sets up the tests to be extensible to test shell
in both beeswax and HS2 modes.
Testing:
* Add test dimension containing only beeswax in preparation
for HS2 dimension.
* Factor out hardcoded ports.
* Add tests for formatting of all types and NULL values.
* Merge date shell test into general type tests.
* Added testing for floating point output formatting, which does
change as a result of switching to server-side vs client-side
formatting.
* Use unique_database for tests that create tables.
Change-Id: Ibe5ab7f4817e690b7d3be08d71f8f14364b84412
Reviewed-on: http://gerrit.cloudera.org:8080/13083
Reviewed-by: Impala Public Jenkins <im...@cloudera.com>
Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
bin/load-data.py | 5 +-
testdata/bin/create-load-data.sh | 2 +-
testdata/bin/create-tpcds-testcase-files.sh | 2 +-
tests/beeswax/impala_beeswax.py | 10 +-
tests/common/impala_test_suite.py | 1 +
tests/common/test_dimensions.py | 4 +
tests/custom_cluster/test_client_ssl.py | 57 +-
tests/custom_cluster/test_shell_interactive.py | 35 +-
.../test_shell_interactive_reconnect.py | 86 +--
tests/query_test/test_date_queries.py | 9 -
tests/shell/test_shell_commandline.py | 603 ++++++++++++---------
tests/shell/test_shell_interactive.py | 518 ++++++++++--------
tests/shell/util.py | 55 +-
13 files changed, 770 insertions(+), 617 deletions(-)
diff --git a/bin/load-data.py b/bin/load-data.py
index 8878372..b461d7a 100755
--- a/bin/load-data.py
+++ b/bin/load-data.py
@@ -55,7 +55,7 @@ parser.add_option("-s", "--scale_factor", dest="scale_factor", default="",
help="An optional scale factor to generate the schema for")
parser.add_option("-f", "--force_reload", dest="force_reload", action="store_true",
default=False, help='Skips HDFS exists check and reloads all tables')
-parser.add_option("--impalad", dest="impalad", default="localhost:21000",
+parser.add_option("--impalad", dest="impalad", default="localhost",
help="Impala daemon to connect to")
parser.add_option("--hive_hs2_hostport", dest="hive_hs2_hostport",
default="localhost:11050",
@@ -191,7 +191,8 @@ def exec_impala_query_from_file(file_name):
LOG.info("Error: File {0} not found".format(file_name))
return False
- LOG.info("Beginning execution of impala SQL: {0}".format(file_name))
+ LOG.info("Beginning execution of impala SQL on {0}: {1}".format(
+ options.impalad, file_name))
is_success = True
impala_client = ImpalaBeeswaxClient(options.impalad, use_kerberos=options.use_kerberos)
output_file = file_name + ".log"
diff --git a/testdata/bin/create-load-data.sh b/testdata/bin/create-load-data.sh
index a5239b1..9796d66 100755
--- a/testdata/bin/create-load-data.sh
+++ b/testdata/bin/create-load-data.sh
@@ -39,7 +39,7 @@ setup_report_build_error
# TODO: We need a better way of managing how these get set. See IMPALA-4346
: ${HS2_HOST_PORT=localhost:11050}
: ${HDFS_NN=${INTERNAL_LISTEN_HOST}:20500}
-: ${IMPALAD=localhost:21000}
+: ${IMPALAD=localhost}
: ${REMOTE_LOAD=}
: ${CM_HOST=}
: ${IMPALA_SERIAL_DATALOAD=}
diff --git a/testdata/bin/create-tpcds-testcase-files.sh b/testdata/bin/create-tpcds-testcase-files.sh
index 42c6897..fd688e8 100755
--- a/testdata/bin/create-tpcds-testcase-files.sh
+++ b/testdata/bin/create-tpcds-testcase-files.sh
@@ -27,7 +27,7 @@ setup_report_build_error
set -x
. ${IMPALA_HOME}/bin/impala-config.sh > /dev/null 2>&1
-IMPALAD=${IMPALAD:-localhost:21000}
+IMPALAD=${IMPALAD:-localhost}
TPCDS_QUERY_HOME=$IMPALA_HOME/testdata/workloads/tpcds/queries/raw
# Target directory containing the testcase data.
diff --git a/tests/beeswax/impala_beeswax.py b/tests/beeswax/impala_beeswax.py
index 08f0c72..e8d43db 100644
--- a/tests/beeswax/impala_beeswax.py
+++ b/tests/beeswax/impala_beeswax.py
@@ -110,7 +110,12 @@ class ImpalaBeeswaxClient(object):
def __init__(self, impalad, use_kerberos=False, user=None, password=None,
use_ssl=False):
self.connected = False
- self.impalad = impalad
+ split_impalad = impalad.split(":")
+ assert len(split_impalad) in [1, 2]
+ self.impalad_host = split_impalad[0]
+ self.impalad_port = 21000 # Default beeswax port
+ if len(split_impalad) == 2:
+ self.impalad_port = int(split_impalad[1])
self.imp_service = None
self.transport = None
self.use_kerberos = use_kerberos
@@ -148,7 +153,6 @@ class ImpalaBeeswaxClient(object):
Raises an exception if the connection is unsuccesful.
"""
try:
- self.impalad = self.impalad.split(':')
self.transport = self.__get_transport()
self.transport.open()
protocol = TBinaryProtocol.TBinaryProtocol(self.transport)
@@ -170,7 +174,7 @@ class ImpalaBeeswaxClient(object):
trans_type = 'kerberos'
elif self.use_ldap:
trans_type = 'plain_sasl'
- return create_transport(host=self.impalad[0], port=int(self.impalad[1]),
+ return create_transport(host=self.impalad_host, port=self.impalad_port,
service='impala', transport_type=trans_type, user=self.user,
password=self.password, use_ssl=self.use_ssl)
diff --git a/tests/common/impala_test_suite.py b/tests/common/impala_test_suite.py
index b25a87f..8b1f54f 100644
--- a/tests/common/impala_test_suite.py
+++ b/tests/common/impala_test_suite.py
@@ -96,6 +96,7 @@ if IS_ADLS:
IMPALAD_HOST_PORT_LIST = pytest.config.option.impalad.split(',')
assert len(IMPALAD_HOST_PORT_LIST) > 0, 'Must specify at least 1 impalad to target'
IMPALAD = IMPALAD_HOST_PORT_LIST[0]
+IMPALAD_BEESWAX_HOST_PORT = IMPALAD_HOST_PORT_LIST[0]
IMPALAD_HS2_HOST_PORT =\
IMPALAD.split(':')[0] + ":" + pytest.config.option.impalad_hs2_port
HIVE_HS2_HOST_PORT = pytest.config.option.hive_server2
diff --git a/tests/common/test_dimensions.py b/tests/common/test_dimensions.py
index 22d9e94..bba1685 100644
--- a/tests/common/test_dimensions.py
+++ b/tests/common/test_dimensions.py
@@ -118,6 +118,10 @@ def create_beeswax_hs2_dimension():
return ImpalaTestDimension('protocol', 'beeswax', 'hs2')
+def create_beeswax_dimension():
+ return ImpalaTestDimension('protocol', 'beeswax')
+
+
def hs2_parquet_constraint(v):
"""Constraint function, used to only run HS2 against Parquet format, because file format
and the client protocol are orthogonal."""
diff --git a/tests/custom_cluster/test_client_ssl.py b/tests/custom_cluster/test_client_ssl.py
index c823be9..848ad8b 100644
--- a/tests/custom_cluster/test_client_ssl.py
+++ b/tests/custom_cluster/test_client_ssl.py
@@ -28,6 +28,7 @@ import time
from tests.common.custom_cluster_test_suite import CustomClusterTestSuite
from tests.common.impala_service import ImpaladService
+from tests.common.test_dimensions import create_beeswax_dimension
from tests.shell.util import run_impala_shell_cmd, run_impala_shell_cmd_no_expect, \
ImpalaShell
@@ -79,18 +80,18 @@ class TestClientSsl(CustomClusterTestSuite):
catalogd_args=SSL_ARGS)
def test_ssl(self, vector):
- self._verify_negative_cases()
+ self._verify_negative_cases(vector)
# TODO: This is really two different tests, but the custom cluster takes too long to
# start. Make it so that custom clusters can be specified across test suites.
- self._validate_positive_cases("%s/server-cert.pem" % self.CERT_DIR)
+ self._validate_positive_cases(vector, "%s/server-cert.pem" % self.CERT_DIR)
# No certificate checking: will accept any cert.
- self._validate_positive_cases()
+ self._validate_positive_cases(vector, )
# Test cancelling a query
impalad = ImpaladService(socket.getfqdn())
assert impalad.wait_for_num_in_flight_queries(0)
- p = ImpalaShell(args="--ssl")
+ p = ImpalaShell(vector, args=["--ssl"])
p.send_cmd("SET DEBUG_ACTION=0:OPEN:WAIT")
p.send_cmd("select count(*) from functional.alltypes")
assert impalad.wait_for_num_in_flight_queries(1)
@@ -120,6 +121,10 @@ class TestClientSsl(CustomClusterTestSuite):
"--hostname=localhost" # Must match hostname in certificate
% {'cert_dir': CERT_DIR})
+ @classmethod
+ def add_test_dimensions(cls):
+ cls.ImpalaTestMatrix.add_dimension(create_beeswax_dimension())
+
@pytest.mark.execute_serially
@CustomClusterTestSuite.with_args(impalad_args=WEBSERVER_SSL_ARGS,
statestored_args=WEBSERVER_SSL_ARGS,
@@ -146,8 +151,8 @@ class TestClientSsl(CustomClusterTestSuite):
@pytest.mark.skipif(sys.version_info < REQUIRED_MIN_PYTHON_VERSION_FOR_TLSV12,
reason="Working around IMPALA-7628. TODO: is the right workaround?")
def test_tls_ecdh(self, vector):
- self._verify_negative_cases()
- self._validate_positive_cases("%s/server-cert.pem" % self.CERT_DIR)
+ self._verify_negative_cases(vector)
+ self._validate_positive_cases(vector, "%s/server-cert.pem" % self.CERT_DIR)
self._verify_ssl_webserver()
# Test that the shell can connect to a TLS1.2 only cluster, and for good measure
@@ -168,11 +173,11 @@ class TestClientSsl(CustomClusterTestSuite):
def test_tls_v12(self, vector):
if sys.version_info < REQUIRED_MIN_PYTHON_VERSION_FOR_TLSV12:
result = run_impala_shell_cmd_no_expect(
- "--ssl -q 'select 1 + 2'", wait_until_connected=False)
+ vector, ["--ssl", "-q", "select 1 + 2"], wait_until_connected=False)
assert "Warning: TLSv1.2 is not supported for Python < 2.7.9" in result.stderr, \
result.stderr
else:
- self._validate_positive_cases("%s/server-cert.pem" % self.CERT_DIR)
+ self._validate_positive_cases(vector, "%s/server-cert.pem" % self.CERT_DIR)
@pytest.mark.execute_serially
@CustomClusterTestSuite.with_args(impalad_args=SSL_WILDCARD_ARGS,
@@ -184,9 +189,9 @@ class TestClientSsl(CustomClusterTestSuite):
""" Test for IMPALA-3159: Test with a certificate which has a wildcard for the
CommonName.
"""
- self._verify_negative_cases()
+ self._verify_negative_cases(vector)
- self._validate_positive_cases("%s/wildcardCA.pem" % self.CERT_DIR)
+ self._validate_positive_cases(vector, "%s/wildcardCA.pem" % self.CERT_DIR)
@pytest.mark.execute_serially
@CustomClusterTestSuite.with_args(impalad_args=SSL_WILDCARD_SAN_ARGS,
@@ -199,41 +204,39 @@ class TestClientSsl(CustomClusterTestSuite):
# This block of code is the same as _validate_positive_cases() but we want to check
# if retrieving the SAN is supported first.
- args = "--ssl -q 'select 1 + 2' --ca_cert=%s/wildcardCA.pem" \
- % self.CERT_DIR
- result = run_impala_shell_cmd_no_expect(args)
+ args = ["--ssl", "-q", "select 1 + 2", "--ca_cert=%s/wildcardCA.pem" % self.CERT_DIR]
+ result = run_impala_shell_cmd_no_expect(vector, args)
if self.SAN_UNSUPPORTED_ERROR in result.stderr:
pytest.xfail("Running with a RHEL/Python combination that has a bug where Python "
"cannot retrieve SAN from certificate: "
"https://bugzilla.redhat.com/show_bug.cgi?id=928390")
- self._verify_negative_cases()
+ self._verify_negative_cases(vector)
- self._validate_positive_cases("%s/wildcardCA.pem" % self.CERT_DIR)
+ self._validate_positive_cases(vector, "%s/wildcardCA.pem" % self.CERT_DIR)
- def _verify_negative_cases(self):
+ def _verify_negative_cases(self, vector):
# Expect the shell to not start successfully if we point --ca_cert to an incorrect
# certificate.
- args = "--ssl -q 'select 1 + 2' --ca_cert=%s/incorrect-commonname-cert.pem" \
- % self.CERT_DIR
- run_impala_shell_cmd(args, expect_success=False)
+ args = ["--ssl", "-q", "select 1 + 2",
+ "--ca_cert=%s/incorrect-commonname-cert.pem" % self.CERT_DIR]
+ run_impala_shell_cmd(vector, args, expect_success=False)
# Expect the shell to not start successfully if we don't specify the --ssl option
- args = "-q 'select 1 + 2'"
- run_impala_shell_cmd(args, expect_success=False)
-
- def _validate_positive_cases(self, ca_cert=""):
- shell_options = "--ssl -q 'select 1 + 2'"
+ args = ["-q", "select 1 + 2"]
+ run_impala_shell_cmd(vector, args, expect_success=False)
- result = run_impala_shell_cmd(shell_options, wait_until_connected=False)
+ def _validate_positive_cases(self, vector, ca_cert=""):
+ shell_options = ["--ssl", "-q", "select 1 + 2"]
+ result = run_impala_shell_cmd(vector, shell_options, wait_until_connected=False)
for msg in [self.SSL_ENABLED, self.CONNECTED, self.FETCHED]:
assert msg in result.stderr
for warning in [self.DEPRECATED_POSITIONAL_WARNING, self.DEPRECATED_VALIDATE_WARNING]:
assert warning not in result.stderr
if ca_cert != "":
- shell_options = shell_options + (" --ca_cert=%s" % ca_cert)
- result = run_impala_shell_cmd(shell_options, wait_until_connected=False)
+ shell_options = shell_options + ["--ca_cert=%s" % ca_cert]
+ result = run_impala_shell_cmd(vector, shell_options, wait_until_connected=False)
for msg in [self.SSL_ENABLED, self.CONNECTED, self.FETCHED]:
assert msg in result.stderr
for warning in [self.DEPRECATED_POSITIONAL_WARNING,
diff --git a/tests/custom_cluster/test_shell_interactive.py b/tests/custom_cluster/test_shell_interactive.py
index 9fde141..254d8e9 100644
--- a/tests/custom_cluster/test_shell_interactive.py
+++ b/tests/custom_cluster/test_shell_interactive.py
@@ -20,8 +20,9 @@ import pexpect
import os
from tests.common.custom_cluster_test_suite import CustomClusterTestSuite
-
-SHELL_CMD = "%s/bin/impala-shell.sh" % os.environ['IMPALA_HOME']
+from tests.common.test_vector import ImpalaTestVector
+from tests.common.test_dimensions import create_beeswax_dimension
+from tests.shell.util import get_shell_cmd, get_impalad_port
class TestShellInteractive(CustomClusterTestSuite):
@@ -36,16 +37,20 @@ class TestShellInteractive(CustomClusterTestSuite):
# Start a long running query so that the next one gets queued.
sleep_query_handle = self.client.execute_async("select sleep(10000)")
self.client.wait_for_admission_control(sleep_query_handle)
- proc = pexpect.spawn(' '.join([SHELL_CMD, "-i localhost:21000"]))
- # Check with only live_summary set to true.
- proc.expect("21000] default>")
- proc.sendline("set live_summary=true;")
- proc.sendline("select 1;")
- proc.expect(expected_admission_status)
- proc.sendcontrol('c')
- proc.expect("Cancelling Query")
- # Check with only live_progress set to true.
- proc.sendline("set live_summary=false;")
- proc.sendline("set live_progress=true;")
- proc.sendline("select 1;")
- proc.expect(expected_admission_status)
+
+ # Iterate over test vector within test function to avoid restarting cluster.
+ for vector in [ImpalaTestVector([value]) for value in create_beeswax_dimension()]:
+ cmd = get_shell_cmd(vector)
+ proc = pexpect.spawn(cmd[0], cmd[1:])
+ # Check with only live_summary set to true.
+ proc.expect("{0}] default>".format(get_impalad_port(vector)))
+ proc.sendline("set live_summary=true;")
+ proc.sendline("select 1;")
+ proc.expect(expected_admission_status)
+ proc.sendcontrol('c')
+ proc.expect("Cancelling Query")
+ # Check with only live_progress set to true.
+ proc.sendline("set live_summary=false;")
+ proc.sendline("set live_progress=true;")
+ proc.sendline("select 1;")
+ proc.expect(expected_admission_status)
diff --git a/tests/custom_cluster/test_shell_interactive_reconnect.py b/tests/custom_cluster/test_shell_interactive_reconnect.py
index 94f1a7e..66a9fcf 100644
--- a/tests/custom_cluster/test_shell_interactive_reconnect.py
+++ b/tests/custom_cluster/test_shell_interactive_reconnect.py
@@ -23,11 +23,12 @@ import os
from tests.common.custom_cluster_test_suite import CustomClusterTestSuite
from tests.common.impala_service import ImpaladService
-from tests.shell.util import ImpalaShell
+from tests.common.test_vector import ImpalaTestVector
+from tests.common.test_dimensions import create_beeswax_dimension
+from tests.shell.util import ImpalaShell, get_shell_cmd, get_impalad_port
# Follow tests/shell/test_shell_interactive.py naming.
from shell.impala_shell import ImpalaShell as ImpalaShellClass
-SHELL_CMD = "%s/bin/impala-shell.sh" % os.environ['IMPALA_HOME']
NUM_QUERIES = 'impala-server.num-queries'
class TestShellInteractiveReconnect(CustomClusterTestSuite):
@@ -38,31 +39,39 @@ class TestShellInteractiveReconnect(CustomClusterTestSuite):
@pytest.mark.execute_serially
def test_manual_reconnect(self):
- p = ImpalaShell()
- p.send_cmd("USE functional")
- p.send_cmd("CONNECT")
- p.send_cmd("SHOW TABLES")
+ # Iterate over test vector within test function to avoid restarting cluster.
+ for vector in [ImpalaTestVector([value]) for value in create_beeswax_dimension()]:
+ p = ImpalaShell(vector)
+ p.send_cmd("USE functional")
+ # Connect without arguments works because the custom cluster will have the default
+ # HS2 and Beeswax ports.
+ p.send_cmd("CONNECT")
+ p.send_cmd("SHOW TABLES")
- result = p.get_result()
- assert "alltypesaggmultifilesnopart" in result.stdout
+ result = p.get_result()
+ assert "alltypesaggmultifilesnopart" in result.stdout, result.stdout
@pytest.mark.execute_serially
def test_auto_reconnect(self):
impalad = ImpaladService(socket.getfqdn())
- start_num_queries = impalad.get_metric_value(NUM_QUERIES)
- p = ImpalaShell()
- p.send_cmd("USE functional")
+ # Iterate over test vector within test function to avoid restarting cluster.
+ for vector in [ImpalaTestVector([value]) for value in create_beeswax_dimension()]:
+ p = ImpalaShell(vector)
+ # ImpalaShell startup may issue query to get server info - get num queries after
+ # starting shell.
+ start_num_queries = impalad.get_metric_value(NUM_QUERIES)
+ p.send_cmd("USE functional")
- # wait for the USE command to finish
- impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 1)
- assert impalad.wait_for_num_in_flight_queries(0)
+ # wait for the USE command to finish
+ impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 1)
+ assert impalad.wait_for_num_in_flight_queries(0)
- self._start_impala_cluster([])
+ self._start_impala_cluster([])
- p.send_cmd("SHOW TABLES")
- result = p.get_result()
- assert "alltypesaggmultifilesnopart" in result.stdout
+ p.send_cmd("SHOW TABLES")
+ result = p.get_result()
+ assert "alltypesaggmultifilesnopart" in result.stdout, result.stdout
@pytest.mark.execute_serially
def test_auto_reconnect_after_impalad_died(self):
@@ -71,24 +80,29 @@ class TestShellInteractiveReconnect(CustomClusterTestSuite):
# to check Disconnect, send_cmd() will no longer have any effect so we can not check
# reconnect.
impalad = ImpaladService(socket.getfqdn())
- start_num_queries = impalad.get_metric_value(NUM_QUERIES)
- proc = pexpect.spawn(' '.join([SHELL_CMD, "-i localhost:21000"]))
- proc.expect("21000] default>")
- proc.sendline("use tpch;")
+ # Iterate over test vector within test function to avoid restarting cluster.
+ for vector in [ImpalaTestVector([value]) for value in create_beeswax_dimension()]:
+ cmd = get_shell_cmd(vector)
+ proc = pexpect.spawn(cmd[0], cmd[1:])
+ proc.expect("{0}] default>".format(get_impalad_port(vector)))
+ # ImpalaShell startup may issue query to get server info - get num queries after
+ # starting shell.
+ start_num_queries = impalad.get_metric_value(NUM_QUERIES)
+ proc.sendline("use tpch;")
- # wait for the USE command to finish
- impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 1)
- assert impalad.wait_for_num_in_flight_queries(0)
+ # wait for the USE command to finish
+ impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 1)
+ assert impalad.wait_for_num_in_flight_queries(0)
- # Disconnect
- self.cluster.impalads[0].kill()
- proc.sendline("show tables;")
- # Search from [1:] since the square brackets "[]" are special characters in regex
- proc.expect(ImpalaShellClass.DISCONNECTED_PROMPT[1:])
- # Restarting Impalad
- self.cluster.impalads[0].start()
- # Check reconnect
- proc.sendline("show tables;")
- proc.expect("nation")
- proc.expect("21000] tpch>")
+ # Disconnect
+ self.cluster.impalads[0].kill()
+ proc.sendline("show tables;")
+ # Search from [1:] since the square brackets "[]" are special characters in regex
+ proc.expect(ImpalaShellClass.DISCONNECTED_PROMPT[1:])
+ # Restarting Impalad
+ self.cluster.impalads[0].start()
+ # Check reconnect
+ proc.sendline("show tables;")
+ proc.expect("nation")
+ proc.expect("{0}] tpch>".format(get_impalad_port(vector)))
diff --git a/tests/query_test/test_date_queries.py b/tests/query_test/test_date_queries.py
index 7c999df..acb0a1e 100644
--- a/tests/query_test/test_date_queries.py
+++ b/tests/query_test/test_date_queries.py
@@ -103,12 +103,3 @@ class TestDateQueries(ImpalaTestSuite):
self.client.execute(SET_PART_FF_SQL)
# Test scanning/writing tables with different fileformats.
self.run_test_case('QueryTest/date-text-only-support', vector, use_db=unique_database)
-
- def test_impala_shell(self):
- """ Test that query returns DATE values through impala-shell. """
- p = ImpalaShell()
- p.send_cmd("set write_delimited=true")
- p.send_cmd('select id_col, date_part, date_col from functional.date_tbl '
- 'order by 1 limit 1')
- result = p.get_result()
- assert '0\t0001-01-01\t0001-01-01' in result.stdout
diff --git a/tests/shell/test_shell_commandline.py b/tests/shell/test_shell_commandline.py
index 666c202..11be9a8 100644
--- a/tests/shell/test_shell_commandline.py
+++ b/tests/shell/test_shell_commandline.py
@@ -21,16 +21,16 @@ import os
import pytest
import re
import signal
-import shlex
import socket
import tempfile
from subprocess import call, Popen
from tests.common.impala_service import ImpaladService
-from tests.common.impala_test_suite import ImpalaTestSuite
+from tests.common.impala_test_suite import ImpalaTestSuite, IMPALAD_HS2_HOST_PORT
from tests.common.skip import SkipIf
+from tests.common.test_dimensions import create_beeswax_dimension
from time import sleep, time
-from util import IMPALAD, SHELL_CMD
+from util import get_impalad_host_port
from util import assert_var_substitution, run_impala_shell_cmd, ImpalaShell
from contextlib import closing
@@ -68,7 +68,7 @@ def empty_table(unique_database, request):
Returns:
fq_table_name (str): the fully qualified name of the table: : dbname.table_name
"""
- table_name = request.node.name
+ table_name = request.node.function.func_name
fq_table_name = '.'.join([unique_database, table_name])
stmt = "CREATE TABLE %s (i integer, s string)" % fq_table_name
request.instance.execute_query_expect_success(request.instance.client, stmt,
@@ -109,57 +109,66 @@ class TestImpalaShell(ImpalaTestSuite):
* Add a test for a kerberized impala.
"""
- def test_no_args(self):
- args = '-q "%s"' % DEFAULT_QUERY
- run_impala_shell_cmd(args)
+ @classmethod
+ def get_workload(self):
+ return 'functional-query'
- def test_multiple_queries(self):
+ @classmethod
+ def add_test_dimensions(cls):
+ cls.ImpalaTestMatrix.add_dimension(create_beeswax_dimension())
+
+ def test_no_args(self, vector):
+ args = ['-q', DEFAULT_QUERY]
+ run_impala_shell_cmd(vector, args)
+
+ def test_multiple_queries(self, vector):
queries = ';'.join([DEFAULT_QUERY] * 3)
- args = '-q "%s" -B' % queries
- run_impala_shell_cmd(args)
+ args = ['-q', queries, '-B']
+ run_impala_shell_cmd(vector, args)
- def test_multiple_queries_with_escaped_backslash(self):
+ def test_multiple_queries_with_escaped_backslash(self, vector):
"""Regression test for string containing an escaped backslash.
This relies on the patch at thirdparty/patches/sqlparse/0001-....patch.
"""
- run_impala_shell_cmd(r'''-q "select '\\\\'; select '\\'';" -B''')
+ run_impala_shell_cmd(vector, ['-q', r'''select '\\'; select '\'';''', '-B'])
- def test_default_db(self, empty_table):
+ def test_default_db(self, vector, empty_table):
db_name, table_name = empty_table.split('.')
- args = '-d %s -q "describe %s" --quiet' % (db_name, table_name)
- run_impala_shell_cmd(args)
- args = '-q "describe %s"' % table_name
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['-d', db_name, '-q', 'describe {0}'.format(table_name), '--quiet']
+ run_impala_shell_cmd(vector, args)
+ args = ['-q', 'describe {0}'.format(table_name)]
+ run_impala_shell_cmd(vector, args, expect_success=False)
# test keyword parquet is interpreted as an identifier
# when passed as an argument to -d
- args = '-d parquet'
- result = run_impala_shell_cmd(args)
+ args = ['-d', 'parquet']
+ result = run_impala_shell_cmd(vector, args)
assert "Query: use `parquet`" in result.stderr, result.stderr
# test if backticking is idempotent
- args = "-d '```parquet```'"
- result = run_impala_shell_cmd(args)
+ args = ['-d', '```parquet```']
+ result = run_impala_shell_cmd(vector, args)
assert "Query: use `parquet`" in result.stderr, result.stderr
- def test_unsecure_message(self):
- results = run_impala_shell_cmd("", wait_until_connected=False)
+ def test_unsecure_message(self, vector):
+ results = run_impala_shell_cmd(vector, [], wait_until_connected=False)
assert "Starting Impala Shell without Kerberos authentication" in results.stderr
- def test_print_header(self, populated_table):
- args = '--print_header -B --output_delim="," -q "select * from %s"' % populated_table
- result = run_impala_shell_cmd(args)
+ def test_print_header(self, vector, populated_table):
+ args = ['--print_header', '-B', '--output_delim=,', '-q',
+ 'select * from {0}'.format(populated_table)]
+ result = run_impala_shell_cmd(vector, args)
result_rows = result.stdout.strip().split('\n')
assert len(result_rows) == 4
assert result_rows[0].split(',') == ['i', 's']
- args = '-B --output_delim="," -q "select * from %s"' % populated_table
- result = run_impala_shell_cmd(args)
+ args = ['-B', '--output_delim=,', '-q', 'select * from {0}'.format(populated_table)]
+ result = run_impala_shell_cmd(vector, args)
result_rows = result.stdout.strip().split('\n')
assert len(result_rows) == 3
@pytest.mark.execute_serially
- def test_kerberos_option(self):
- args = "-k"
+ def test_kerberos_option(self, vector):
+ args = ['-k']
# If you have a valid kerberos ticket in your cache, this test fails - so
# here we set a bogus KRB5CCNAME in the environment so that klist (and other
@@ -168,7 +177,7 @@ class TestImpalaShell(ImpalaTestSuite):
os.environ["KRB5CCNAME"] = "/tmp/this/file/hopefully/does/not/exist"
# The command will fail because we're trying to connect to a kerberized impalad.
- results = run_impala_shell_cmd(args, expect_success=False)
+ results = run_impala_shell_cmd(vector, args, expect_success=False)
# Check that impala is using the right service name.
assert "Using service name 'impala'" in results.stderr
assert "Starting Impala Shell using Kerberos authentication" in results.stderr
@@ -184,164 +193,166 @@ class TestImpalaShell(ImpalaTestSuite):
# Make sure we don't try to re-connect
assert "retrying the connection with a secure transport" not in results.stderr
# Change the service name
- args += " -s foobar"
- results = run_impala_shell_cmd(args, expect_success=False)
+ args += ['-s', 'foobar']
+ results = run_impala_shell_cmd(vector, args, expect_success=False)
assert "Using service name 'foobar'" in results.stderr
- def test_continue_on_error(self):
- args = '-c -q "select foo; select bar;"'
- run_impala_shell_cmd(args)
+ def test_continue_on_error(self, vector):
+ args = ['-c', '-q', 'select foo; select bar;']
+ run_impala_shell_cmd(vector, args)
# Should fail
- args = '-q "select foo; select bar;"'
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'select foo; select bar;']
+ run_impala_shell_cmd(vector, args, expect_success=False)
- def test_execute_queries_from_file(self):
- args = '-f %s/test_file_comments.sql --quiet -B' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ def test_execute_queries_from_file(self, vector):
+ args = ['-f', '{0}/test_file_comments.sql'.format(QUERY_FILE_PATH), '--quiet', '-B']
+ result = run_impala_shell_cmd(vector, args)
output = result.stdout
- args = '-f %s/test_file_no_comments.sql --quiet -B' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ args = ['-f', '{0}/test_file_no_comments.sql'.format(QUERY_FILE_PATH), '--quiet',
+ '-B']
+ result = run_impala_shell_cmd(vector, args)
assert output == result.stdout, "Queries with comments not parsed correctly"
- def test_completed_query_errors(self):
- args = ('-q "set abort_on_error=false;'
- ' select count(*) from functional_seq_snap.bad_seq_snap"')
- result = run_impala_shell_cmd(args)
+ def test_completed_query_errors(self, vector):
+ args = ['-q', 'set abort_on_error=false;'
+ 'select count(*) from functional_seq_snap.bad_seq_snap']
+ result = run_impala_shell_cmd(vector, args)
assert 'WARNINGS:' in result.stderr
assert 'Bad synchronization marker' in result.stderr
assert 'Expected: ' in result.stderr
assert 'Actual: ' in result.stderr
assert 'Problem parsing file' in result.stderr
- def test_completed_query_errors_1(self):
- args = ('-q "set abort_on_error=true;'
- ' select id from functional_parquet.bad_column_metadata t"')
- result = run_impala_shell_cmd(args, expect_success=False)
+ def test_completed_query_errors_1(self, vector):
+ args = ['-q', 'set abort_on_error=true;'
+ 'select id from functional_parquet.bad_column_metadata t']
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
assert 'ERROR: Column metadata states there are 11 values, ' in result.stderr
assert 'but read 10 values from column id.' in result.stderr
- def test_completed_query_errors_2(self):
- args = ('-q "set abort_on_error=true;'
- ' select id, cnt from functional_parquet.bad_column_metadata t,'
- ' (select 1 cnt) u"')
- result = run_impala_shell_cmd(args, expect_success=False)
- assert 'ERROR: Column metadata states there are 11 values, ' in result.stderr
- assert 'but read 10 values from column id.' in result.stderr
+ def test_completed_query_errors_2(self, vector):
+ args = ['-q', 'set abort_on_error=true; '
+ 'select id, cnt from functional_parquet.bad_column_metadata t, '
+ '(select 1 cnt) u']
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
+ assert 'ERROR: Column metadata states there are 11 values, ' in result.stderr,\
+ result.stderr
+ assert 'but read 10 values from column id.' in result.stderr, result.stderr
- def test_no_warnings_in_log_with_quiet_mode(self):
+ def test_no_warnings_in_log_with_quiet_mode(self, vector):
"""Regression test for IMPALA-4222."""
- args = ('-q "set abort_on_error=false;'
- ' select count(*) from functional_seq_snap.bad_seq_snap" --quiet')
- result = run_impala_shell_cmd(args)
- assert 'WARNINGS:' not in result.stderr
+ args = ['--quiet', '-q', 'set abort_on_error=false;'
+ 'select count(*) from functional_seq_snap.bad_seq_snap']
+ result = run_impala_shell_cmd(vector, args)
+ assert 'WARNINGS:' not in result.stderr, result.stderr
- def test_removed_query_option(self):
+ def test_removed_query_option(self, vector):
"""Test that removed query options produce warning."""
- result = run_impala_shell_cmd("-q 'set disable_cached_reads=true'",
+ result = run_impala_shell_cmd(vector, ['-q', 'set disable_cached_reads=true'],
expect_success=True)
- assert "Ignoring removed query option: 'disable_cached_reads'" in result.stderr
+ assert "Ignoring removed query option: 'disable_cached_reads'" in result.stderr,\
+ result.stderr
- def test_output_format(self):
+ def test_output_format(self, vector):
expected_output = ['1'] * 3
- args = '-q "select 1,1,1" -B --quiet'
- result = run_impala_shell_cmd(args)
+ args = ['-q', 'select 1,1,1', '-B', '--quiet']
+ result = run_impala_shell_cmd(vector, args)
actual_output = [r.strip() for r in result.stdout.split('\t')]
assert actual_output == expected_output
- result = run_impala_shell_cmd(args + ' --output_delim="|"')
+ result = run_impala_shell_cmd(vector, args + ['--output_delim=|'])
actual_output = [r.strip() for r in result.stdout.split('|')]
assert actual_output == expected_output
- result = run_impala_shell_cmd(args + ' --output_delim="||"',
+ result = run_impala_shell_cmd(vector, args + ['--output_delim=||'],
expect_success=False)
assert "Illegal delimiter" in result.stderr
- def test_do_methods(self, empty_table):
+ def test_do_methods(self, vector, empty_table):
"""Ensure that the do_ methods in the shell work.
Some of the do_ methods are implicitly tested in other tests, and as part of the
test setup.
"""
# explain
- args = '-q "explain select 1"'
- run_impala_shell_cmd(args)
+ args = ['-q', 'explain select 1']
+ run_impala_shell_cmd(vector, args)
# show
- args = '-q "show tables"'
- run_impala_shell_cmd(args)
+ args = ['-q', 'show tables']
+ run_impala_shell_cmd(vector, args)
# with
- args = '-q "with t1 as (select 1) select * from t1"'
- run_impala_shell_cmd(args)
+ args = ['-q', 'with t1 as (select 1) select * from t1']
+ run_impala_shell_cmd(vector, args)
# set
# spaces around the = sign
- args = '-q "set batch_size = 10"'
- run_impala_shell_cmd(args)
+ args = ['-q', 'set batch_size = 10']
+ run_impala_shell_cmd(vector, args)
# no spaces around the = sign
- args = '-q "set batch_size=10"'
- run_impala_shell_cmd(args)
+ args = ['-q', 'set batch_size=10']
+ run_impala_shell_cmd(vector, args)
# test query options displayed
- args = '-q "set"'
- result_set = run_impala_shell_cmd(args)
+ args = ['-q', 'set']
+ result_set = run_impala_shell_cmd(vector, args)
assert 'MEM_LIMIT: [0]' in result_set.stdout
# test to check that explain_level is STANDARD
assert 'EXPLAIN_LEVEL: [STANDARD]' in result_set.stdout
# test to check that configs without defaults show up as []
assert 'COMPRESSION_CODEC: []' in result_set.stdout
# test values displayed after setting value
- args = '-q "set mem_limit=1g;set"'
- result_set = run_impala_shell_cmd(args)
+ args = ['-q', 'set mem_limit=1g;set']
+ result_set = run_impala_shell_cmd(vector, args)
# single list means one instance of mem_limit in displayed output
assert 'MEM_LIMIT: 1g' in result_set.stdout
assert 'MEM_LIMIT: [0]' not in result_set.stdout
# Negative tests for set
# use : instead of =
- args = '-q "set batch_size:10"'
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'set batch_size:10']
+ run_impala_shell_cmd(vector, args, expect_success=False)
# use 2 = signs
- args = '-q "set batch_size=10=50"'
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'set batch_size=10=50']
+ run_impala_shell_cmd(vector, args, expect_success=False)
# describe and desc should return the same result.
- args = '-q "describe %s" -B' % empty_table
- result_describe = run_impala_shell_cmd(args)
- args = '-q "desc %s" -B' % empty_table
- result_desc = run_impala_shell_cmd(args)
+ args = ['-q', 'describe {0}'.format(empty_table), '-B']
+ result_describe = run_impala_shell_cmd(vector, args)
+ args = ['-q', 'desc {0}'.format(empty_table), '-B']
+ result_desc = run_impala_shell_cmd(vector, args)
assert result_describe.stdout == result_desc.stdout
- def test_runtime_profile(self):
+ def test_runtime_profile(self, vector):
# test summary is in both the profile printed by the
# -p option and the one printed by the profile command
- args = "-p -q 'select 1; profile;'"
- result_set = run_impala_shell_cmd(args)
+ args = ['-p', '-q', 'select 1; profile;']
+ result_set = run_impala_shell_cmd(vector, args)
# This regex helps us uniquely identify a profile.
regex = re.compile("Operator\s+#Hosts\s+Avg\s+Time")
# We expect two query profiles.
assert len(re.findall(regex, result_set.stdout)) == 2, \
"Could not detect two profiles, stdout: %s" % result_set.stdout
- def test_summary(self):
- args = "-q 'select count(*) from functional.alltypes; summary;'"
- result_set = run_impala_shell_cmd(args)
+ def test_summary(self, vector):
+ args = ['-q', 'select count(*) from functional.alltypes; summary;']
+ result_set = run_impala_shell_cmd(vector, args)
assert "03:AGGREGATE" in result_set.stdout
- args = "-q 'summary;'"
- result_set = run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'summary;']
+ result_set = run_impala_shell_cmd(vector, args, expect_success=False)
assert "Could not retrieve summary for query" in result_set.stderr
- args = "-q 'show tables; summary;'"
- result_set = run_impala_shell_cmd(args)
+ args = ['-q', 'show tables; summary;']
+ result_set = run_impala_shell_cmd(vector, args)
assert "Summary not available" in result_set.stderr
# Test queries without an exchange
- args = "-q 'select 1; summary;'"
- result_set = run_impala_shell_cmd(args)
+ args = ['-q', 'select 1; summary;']
+ result_set = run_impala_shell_cmd(vector, args)
assert "00:UNION" in result_set.stdout
@pytest.mark.execute_serially
- def test_queries_closed(self):
+ def test_queries_closed(self, vector):
"""Regression test for IMPALA-897."""
- args = '-f %s/test_close_queries.sql --quiet -B' % QUERY_FILE_PATH
- cmd = "%s %s" % (SHELL_CMD, args)
+ args = ['-f', '{0}/test_close_queries.sql'.format(QUERY_FILE_PATH), '--quiet', '-B']
# Execute the shell command async
- p = ImpalaShell(args)
+ p = ImpalaShell(vector, args)
- impalad_service = ImpaladService(IMPALAD.split(':')[0])
+ impalad_service = ImpaladService(get_impalad_host_port(vector).split(':')[0])
# The last query in the test SQL script will sleep for 10 seconds, so sleep
# here for 5 seconds and verify the number of in-flight queries is 1.
sleep(5)
@@ -349,21 +360,20 @@ class TestImpalaShell(ImpalaTestSuite):
assert p.get_result().rc == 0
assert 0 == impalad_service.get_num_in_flight_queries()
- def test_cancellation(self):
+ def test_cancellation(self, vector):
"""Test cancellation (Ctrl+C event). Run a query that sleeps 10ms per row so will run
for 110s if not cancelled, but will detect cancellation quickly because of the small
batch size."""
query = "set num_nodes=1; set mt_dop=1; set batch_size=1; \
select sleep(10) from functional_parquet.alltypesagg"
- p = ImpalaShell('-q "{0}"'.format(query))
+ p = ImpalaShell(vector, ['-q', query])
p.wait_for_query_start()
os.kill(p.pid(), signal.SIGINT)
result = p.get_result()
-
assert "Cancelling Query" in result.stderr, result.stderr
@pytest.mark.execute_serially
- def test_query_cancellation_during_fetch(self):
+ def test_query_cancellation_during_fetch(self, vector):
"""IMPALA-1144: Test cancellation (CTRL+C) while results are being
fetched"""
pytest.skip("""Skipping as it occasionally gets stuck in Jenkins builds
@@ -373,24 +383,24 @@ class TestImpalaShell(ImpalaTestSuite):
"select * from v, v v2, v v3, v v4, v v5, v v6, v v7, v v8, " + \
"v v9, v v10, v v11"
# Kill happens when the results are being fetched
- self.run_and_verify_query_cancellation_test(stmt, "FINISHED")
+ self.run_and_verify_query_cancellation_test(vector, stmt, "FINISHED")
@pytest.mark.execute_serially
- def test_query_cancellation_during_wait_to_finish(self):
+ def test_query_cancellation_during_wait_to_finish(self, vector):
"""IMPALA-1144: Test cancellation (CTRL+C) while the query is in the
wait_to_finish state"""
# A select where wait_to_finish takes several seconds
stmt = "select * from tpch.customer c1, tpch.customer c2, " + \
"tpch.customer c3 order by c1.c_name"
# Kill happens in wait_to_finish state
- self.run_and_verify_query_cancellation_test(stmt, "RUNNING")
+ self.run_and_verify_query_cancellation_test(vector, stmt, "RUNNING")
- def wait_for_query_state(self, stmt, state, max_retry=15):
+ def wait_for_query_state(self, vector, stmt, state, max_retry=15):
"""Checks the in flight queries on Impala debug page. Polls the state of
the query statement from parameter every second until the query gets to
a state given via parameter or a maximum retry count is reached.
Restriction: Only works if there is only one in flight query."""
- impalad_service = ImpaladService(IMPALAD.split(':')[0])
+ impalad_service = ImpaladService(get_impalad_host_port(vector).split(':')[0])
if not impalad_service.wait_for_num_in_flight_queries(1):
raise Exception("No in flight query found")
@@ -407,84 +417,82 @@ class TestImpalaShell(ImpalaTestSuite):
sleep(1.0)
raise Exception("Query didn't reach desired state: " + state)
- def run_and_verify_query_cancellation_test(self, stmt, cancel_at_state):
+ def run_and_verify_query_cancellation_test(self, vector, stmt, cancel_at_state):
"""Starts the execution of the received query, waits until the query
execution in fact starts and then cancels it. Expects the query
cancellation to succeed."""
- args = "-q \"" + stmt + ";\""
- p = ImpalaShell(args)
+ p = ImpalaShell(vector, ['-q', stmt])
- self.wait_for_query_state(stmt, cancel_at_state)
+ self.wait_for_query_state(vector, stmt, cancel_at_state)
os.kill(p.pid(), signal.SIGINT)
result = p.get_result()
assert "Cancelling Query" in result.stderr
assert "Invalid query handle" not in result.stderr
- def test_get_log_once(self, empty_table):
+ def test_get_log_once(self, vector, empty_table):
"""Test that get_log() is always called exactly once."""
# Query with fetch
- args = '-q "select * from functional.alltypeserror"'
- result = run_impala_shell_cmd(args)
+ args = ['-q', 'select * from functional.alltypeserror']
+ result = run_impala_shell_cmd(vector, args)
assert result.stderr.count('WARNINGS') == 1
# Insert query (doesn't fetch)
- drop_args = '-q "drop table if exists %s"' % empty_table
- run_impala_shell_cmd(drop_args)
+ drop_args = ['-q', 'drop table if exists {0}'.format(empty_table)]
+ run_impala_shell_cmd(vector, drop_args)
- args = '-q "create table %s like functional.alltypeserror"' % empty_table
- run_impala_shell_cmd(args)
+ args = ['-q', 'create table {0} like functional.alltypeserror'.format(empty_table)]
+ run_impala_shell_cmd(vector, args)
- args = '-q "insert overwrite %s partition(year, month)' \
- 'select * from functional.alltypeserror"' % empty_table
- result = run_impala_shell_cmd(args)
+ args = ['-q', 'insert overwrite {0} partition(year, month)'
+ 'select * from functional.alltypeserror'.format(empty_table)]
+ result = run_impala_shell_cmd(vector, args)
assert result.stderr.count('WARNINGS') == 1
- def test_international_characters(self):
+ def test_international_characters(self, vector):
"""Sanity test to ensure that the shell can read international characters."""
- args = """-B -q "select '%s'" """ % RUSSIAN_CHARS
- result = run_impala_shell_cmd(args.encode('utf-8'))
+ args = ['-B', '-q', "select '{0}'".format(RUSSIAN_CHARS.encode('utf-8'))]
+ result = run_impala_shell_cmd(vector, args)
assert 'UnicodeDecodeError' not in result.stderr
assert RUSSIAN_CHARS.encode('utf-8') in result.stdout
- def test_international_characters_prettyprint(self):
+ def test_international_characters_prettyprint(self, vector):
"""IMPALA-2717: ensure we can handle international characters in pretty-printed
output"""
- args = """-q "select '%s'" """ % RUSSIAN_CHARS
- result = run_impala_shell_cmd(args.encode('utf-8'))
+ args = ['-q', "select '{0}'".format(RUSSIAN_CHARS.encode('utf-8'))]
+ result = run_impala_shell_cmd(vector, args)
assert 'UnicodeDecodeError' not in result.stderr
assert RUSSIAN_CHARS.encode('utf-8') in result.stdout
- def test_international_characters_prettyprint_tabs(self):
+ def test_international_characters_prettyprint_tabs(self, vector):
"""IMPALA-2717: ensure we can handle international characters in pretty-printed
output when pretty-printing falls back to delimited output."""
- args = """-q "select '%s\\t'" """ % RUSSIAN_CHARS
- result = run_impala_shell_cmd(args.encode('utf-8'))
+ args = ['-q', "select '{0}\\t'".format(RUSSIAN_CHARS.encode('utf-8'))]
+ result = run_impala_shell_cmd(vector, args)
assert 'Reverting to tab delimited text' in result.stderr
assert 'UnicodeDecodeError' not in result.stderr
assert RUSSIAN_CHARS.encode('utf-8') in result.stdout
@pytest.mark.execute_serially # This tests invalidates metadata, and must run serially
- def test_config_file(self):
+ def test_config_file(self, vector):
"""Test the optional configuration file."""
# Positive tests
- args = '--config_file=%s/good_impalarc' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ args = ['--config_file=%s/good_impalarc' % QUERY_FILE_PATH]
+ result = run_impala_shell_cmd(vector, args)
assert 'WARNING:' not in result.stderr
assert 'Query: select 1' in result.stderr
# override option in config file through command line
- args = '--config_file=%s/good_impalarc --query="select 2"' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ args = ['--config_file={0}/good_impalarc'.format(QUERY_FILE_PATH), '--query=select 2']
+ result = run_impala_shell_cmd(vector, args)
assert 'Query: select 2' in result.stderr
# IMPALA-8317: Add support for list-type, i.e. action=append in config file.
- args = '--config_file=%s/good_impalarc ' \
- '--query="select \'${VAR:msg1}\'; select \'${VAR:msg2}\'; ' \
- 'select \'${VAR:msg3}\'; select \'${VAR:msg4}\'; set"' % \
- QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ args = ['--config_file={0}/good_impalarc'.format(QUERY_FILE_PATH),
+ """--query=select '${VAR:msg1}'; select '${VAR:msg2}';
+ select '${VAR:msg3}'; select '${VAR:msg4}'; set"""]
+ result = run_impala_shell_cmd(vector, args)
assert 'Query: select \'hello\'' in result.stderr
assert 'Query: select \'world\'' in result.stderr
assert 'Query: select \'foo\'' in result.stderr
@@ -492,39 +500,39 @@ class TestImpalaShell(ImpalaTestSuite):
assert 'DEFAULT_FILE_FORMAT: parquet' in result.stdout
# Override the variables in the config file with the ones passed via --var.
- args = '--config_file=%s/good_impalarc --var=msg1=foo --var=msg2=bar ' \
- '--query="select \'${VAR:msg1}\'; select \'${VAR:msg2}\'"' % \
- QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ args = ['--config_file={0}/good_impalarc'.format(QUERY_FILE_PATH), '--var=msg1=foo',
+ '--var=msg2=bar', """--query=select '${VAR:msg1}'; select '${VAR:msg2}'"""]
+ result = run_impala_shell_cmd(vector, args)
assert 'Query: select \'foo\'' in result.stderr
assert 'Query: select \'bar\'' in result.stderr
# Negative Tests
# specified config file does not exist
- args = '--config_file=%s/does_not_exist' % QUERY_FILE_PATH
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['--config_file=%s/does_not_exist' % QUERY_FILE_PATH]
+ run_impala_shell_cmd(vector, args, expect_success=False)
# bad formatting of config file
- args = '--config_file=%s/bad_impalarc' % QUERY_FILE_PATH
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['--config_file=%s/bad_impalarc' % QUERY_FILE_PATH]
+ run_impala_shell_cmd(vector, args, expect_success=False)
# Testing config file related warning and error messages
- args = '--config_file=%s/impalarc_with_warnings' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args, expect_success=True, wait_until_connected=False)
+ args = ['--config_file=%s/impalarc_with_warnings' % QUERY_FILE_PATH]
+ result = run_impala_shell_cmd(
+ vector, args, expect_success=True, wait_until_connected=False)
assert "WARNING: Option 'config_file' can be only set from shell." in result.stderr
err_msg = ("WARNING: Unable to read configuration file correctly. "
"Ignoring unrecognized config option: 'invalid_option'\n")
assert err_msg in result.stderr
- args = '--config_file=%s/impalarc_with_error' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args, expect_success=False)
+ args = ['--config_file=%s/impalarc_with_error' % QUERY_FILE_PATH]
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
err_msg = ("Unexpected value in configuration file. "
"'maybe' is not a valid value for a boolean option.")
assert err_msg in result.stderr
- def test_execute_queries_from_stdin(self):
+ def test_execute_queries_from_stdin(self, vector):
"""Test that queries get executed correctly when STDIN is given as the sql file."""
- args = '-f - --quiet -B'
- query_file = "%s/test_file_comments.sql" % QUERY_FILE_PATH
+ args = ['-f', '-', '--quiet', '-B']
+ query_file = "{0}/test_file_comments.sql".format(QUERY_FILE_PATH)
query_file_handle = None
try:
query_file_handle = open(query_file, 'r')
@@ -532,16 +540,17 @@ class TestImpalaShell(ImpalaTestSuite):
query_file_handle.close()
except Exception, e:
assert query_file_handle is not None, "Exception %s: Could not find query file" % e
- result = run_impala_shell_cmd(args, expect_success=True, stdin_input=query)
+ result = run_impala_shell_cmd(vector, args, expect_success=True, stdin_input=query)
output = result.stdout
- args = '-f %s/test_file_no_comments.sql --quiet -B' % QUERY_FILE_PATH
- result = run_impala_shell_cmd(args)
+ args = ['-f', '{0}/test_file_no_comments.sql'.format(QUERY_FILE_PATH), '--quiet',
+ '-B']
+ result = run_impala_shell_cmd(vector, args)
assert output == result.stdout, "Queries from STDIN not parsed correctly."
- def test_allow_creds_in_clear(self):
- args = '-l'
- result = run_impala_shell_cmd(args, expect_success=False)
+ def test_allow_creds_in_clear(self, vector):
+ args = ['-l']
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
err_msg = ("LDAP credentials may not be sent over insecure connections. "
"Enable SSL or set --auth_creds_ok_in_clear")
@@ -550,48 +559,50 @@ class TestImpalaShell(ImpalaTestSuite):
# TODO: Without an Impala daemon running LDAP authentication, we can't test if
# --auth_creds_ok_in_clear works when correctly set.
- def test_ldap_password_from_shell(self):
- args = "-l --auth_creds_ok_in_clear --ldap_password_cmd='%s'"
- result = run_impala_shell_cmd(args % 'cmddoesntexist', expect_success=False)
+ def test_ldap_password_from_shell(self, vector):
+ args = ['-l', '--auth_creds_ok_in_clear']
+ result = run_impala_shell_cmd(vector, args + ['--ldap_password_cmd=cmddoesntexist'],
+ expect_success=False)
assert ("Error retrieving LDAP password (command was: 'cmddoesntexist', exception "
"was: '[Errno 2] No such file or directory')") in result.stderr
- result = run_impala_shell_cmd(args % 'cat filedoesntexist', expect_success=False)
+ result = run_impala_shell_cmd(
+ vector, args + ['--ldap_password_cmd=cat filedoesntexist'], expect_success=False)
assert ("Error retrieving LDAP password (command was 'cat filedoesntexist', error "
"was: 'cat: filedoesntexist: No such file or directory')") in result.stderr
# TODO: Without an Impala daemon with LDAP authentication enabled, we can't test the
# positive case where the password is correct.
- def test_var_substitution(self):
- args = '--var=foo=123 --var=BAR=456 --delimited --output_delimiter=" " -c -f %s' \
- % (os.path.join(QUERY_FILE_PATH, 'test_var_substitution.sql'))
- result = run_impala_shell_cmd(args, expect_success=True)
+ def test_var_substitution(self, vector):
+ args = ['--var=foo=123', '--var=BAR=456', '--delimited', '--output_delimiter= ',
+ '-c', '-f', os.path.join(QUERY_FILE_PATH, 'test_var_substitution.sql')]
+ result = run_impala_shell_cmd(vector, args, expect_success=True)
assert_var_substitution(result)
- args = '--var=foo'
- result = run_impala_shell_cmd(args, expect_success=False)
+ args = ['--var=foo']
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
assert ("Error: Could not parse key-value \"foo\". It must follow the pattern "
"\"KEY=VALUE\".") in result.stderr
# IMPALA-7673: Test that variable substitution in command line can accept values
# from other variables just like the one in interactive shell.
- result = run_impala_shell_cmd('--var="msg1=1" --var="msg2=${var:msg1}2" '
- '--var="msg3=${var:msg1}${var:msg2}" '
- '--query="select ${var:msg3}"')
+ result = run_impala_shell_cmd(vector, [
+ '--var=msg1=1', '--var=msg2=${var:msg1}2', '--var=msg3=${var:msg1}${var:msg2}',
+ '--query=select ${var:msg3}'])
self._validate_shell_messages(result.stderr, ['112', 'Fetched 1 row(s)'],
should_exist=True)
# Test with an escaped variable.
- result = run_impala_shell_cmd('--var="msg1=1" --var="msg2=${var:msg1}2" '
- '--var="msg3=\${var:msg1}${var:msg2}" '
- '--query="select \'${var:msg3}\'"')
+ result = run_impala_shell_cmd(vector, ['--var=msg1=1', '--var=msg2=${var:msg1}2',
+ '--var=msg3=\${var:msg1}${var:msg2}',
+ "--query=select '${var:msg3}'"])
self._validate_shell_messages(result.stderr, ['${var:msg1}12', 'Fetched 1 row(s)'],
should_exist=True)
# Referencing a non-existent variable will result in an error.
- result = run_impala_shell_cmd('--var="msg1=1" --var="msg2=${var:doesnotexist}2" '
- '--var="msg3=\${var:msg1}${var:msg2}" '
- '--query="select \'${var:msg3}\'"',
- expect_success=False)
+ result = run_impala_shell_cmd(vector, [
+ '--var=msg1=1', '--var=msg2=${var:doesnotexist}2',
+ '--var=msg3=\${var:msg1}${var:msg2}', "--query=select '${var:msg3}'"],
+ expect_success=False)
self._validate_shell_messages(result.stderr,
['Error: Unknown variable DOESNOTEXIST',
'Could not execute command: select \'${var:msg3}\''],
@@ -602,100 +613,106 @@ class TestImpalaShell(ImpalaTestSuite):
def _validate_shell_messages(self, result_stderr, messages, should_exist=True):
for msg in messages:
if should_exist:
- assert msg in result_stderr
+ assert msg in result_stderr, result_stderr
else:
- assert msg not in result_stderr
+ assert msg not in result_stderr, result_stderr
- def test_query_time_and_link_message(self, unique_database):
+ def test_query_time_and_link_message(self, vector, unique_database):
shell_messages = ["Query submitted at: ", "(Coordinator: ",
"Query progress can be monitored at: "]
# CREATE statements should not print query time and webserver address.
- results = run_impala_shell_cmd('--query="create table %s.shell_msg_test (id int)"' %
- unique_database)
+ results = run_impala_shell_cmd(
+ vector, ['--query=create table %s.shell_msg_test (id int)' % unique_database])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=False)
# SELECT, INSERT, CTAS, CTE queries should print the query time message and webserver
# address.
- results = run_impala_shell_cmd('--query="insert into %s.shell_msg_test values (1)"' %
- unique_database)
+ results = run_impala_shell_cmd(
+ vector, ['--query=insert into %s.shell_msg_test values (1)' % unique_database])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=True)
- results = run_impala_shell_cmd('--query="select * from %s.shell_msg_test"' %
- unique_database)
+ results = run_impala_shell_cmd(
+ vector, ['--query=select * from %s.shell_msg_test' % unique_database])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=True)
- results = run_impala_shell_cmd('--query="create table %s.shell_msg_ctas_test as \
- select * from %s.shell_msg_test"' % (unique_database, unique_database))
+ results = run_impala_shell_cmd(vector, [
+ '--query=create table %s.shell_msg_ctas_test as \
+ select * from %s.shell_msg_test' % (unique_database, unique_database)])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=True)
- results = run_impala_shell_cmd('--query="create table %s.shell_msg_cte_test(i int); '
- 'with abc as (select 1) '
- 'insert overwrite %s.shell_msg_cte_test '
- 'select * from %s.shell_msg_cte_test;"' %
- (unique_database, unique_database, unique_database))
+ results = run_impala_shell_cmd(vector, [
+ '--query=create table {db}.shell_msg_cte_test(i int); '
+ 'with abc as (select 1) '
+ 'insert overwrite {db}.shell_msg_cte_test '
+ 'select * from {db}.shell_msg_cte_test;'.format(db=unique_database)])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=True)
# DROP statements should not print query time and webserver address.
- results = run_impala_shell_cmd('--query="drop table %s.shell_msg_test"' %
- unique_database)
+ results = run_impala_shell_cmd(
+ vector, ['--query=drop table %s.shell_msg_test' % unique_database])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=False)
- run_impala_shell_cmd('--query="drop table %s.shell_msg_ctas_test"' %
- unique_database)
+ run_impala_shell_cmd(
+ vector, ['--query=drop table %s.shell_msg_ctas_test' % unique_database])
# Simple queries should not print query time and webserver address.
- results = run_impala_shell_cmd('--query="use default"')
+ results = run_impala_shell_cmd(vector, ['--query=use default'])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=False)
- results = run_impala_shell_cmd('--query="show tables"')
+ results = run_impala_shell_cmd(vector, ['--query=show tables'])
self._validate_shell_messages(results.stderr, shell_messages, should_exist=False)
- def test_insert_status(self, unique_database):
- run_impala_shell_cmd('--query="create table %s.insert_test (id int)"' %
- unique_database)
- results = run_impala_shell_cmd('--query="insert into %s.insert_test values (1)"' %
- unique_database)
+ def test_insert_status(self, vector, unique_database):
+ run_impala_shell_cmd(
+ vector, ['--query=create table %s.insert_test (id int)' % unique_database])
+ results = run_impala_shell_cmd(
+ vector, ['--query=insert into %s.insert_test values (1)' % unique_database])
assert "Modified 1 row(s)" in results.stderr
- def _validate_dml_stmt(self, stmt, expected_rows_modified, expected_row_errors):
- results = run_impala_shell_cmd('--query="%s"' % (stmt))
+ def _validate_dml_stmt(self, vector, stmt, expected_rows_modified, expected_row_errors):
+ results = run_impala_shell_cmd(vector, ['--query=%s' % stmt])
expected_output = "Modified %d row(s), %d row error(s)" %\
(expected_rows_modified, expected_row_errors)
assert expected_output in results.stderr, results.stderr
@SkipIf.kudu_not_supported
- def test_kudu_dml_reporting(self, unique_database):
+ def test_kudu_dml_reporting(self, vector, unique_database):
db = unique_database
- run_impala_shell_cmd('--query="create table %s.dml_test (id int primary key, '\
- 'age int null) partition by hash(id) partitions 2 stored as kudu"' % db)
-
- self._validate_dml_stmt("insert into %s.dml_test (id) values (7), (7)" % db, 1, 1)
- self._validate_dml_stmt("insert into %s.dml_test (id) values (7)" % db, 0, 1)
- self._validate_dml_stmt("upsert into %s.dml_test (id) values (7), (7)" % db, 2, 0)
- self._validate_dml_stmt("update %s.dml_test set age = 1 where id = 7" % db, 1, 0)
- self._validate_dml_stmt("delete from %s.dml_test where id = 7" % db, 1, 0)
+ run_impala_shell_cmd(vector, [
+ '--query=create table %s.dml_test (id int primary key, '
+ 'age int null) partition by hash(id) partitions 2 stored as kudu' % db])
+
+ self._validate_dml_stmt(
+ vector, "insert into %s.dml_test (id) values (7), (7)" % db, 1, 1)
+ self._validate_dml_stmt(vector, "insert into %s.dml_test (id) values (7)" % db, 0, 1)
+ self._validate_dml_stmt(
+ vector, "upsert into %s.dml_test (id) values (7), (7)" % db, 2, 0)
+ self._validate_dml_stmt(
+ vector, "update %s.dml_test set age = 1 where id = 7" % db, 1, 0)
+ self._validate_dml_stmt(vector, "delete from %s.dml_test where id = 7" % db, 1, 0)
# UPDATE/DELETE where there are no matching rows; there are no errors because the
# scan produced no rows.
- self._validate_dml_stmt("update %s.dml_test set age = 1 where id = 8" % db, 0, 0)
- self._validate_dml_stmt("delete from %s.dml_test where id = 7" % db, 0, 0)
+ self._validate_dml_stmt(
+ vector, "update %s.dml_test set age = 1 where id = 8" % db, 0, 0)
+ self._validate_dml_stmt(vector, "delete from %s.dml_test where id = 7" % db, 0, 0)
# WITH clauses, only apply to INSERT and UPSERT
- self._validate_dml_stmt(\
+ self._validate_dml_stmt(vector,
"with y as (values(7)) insert into %s.dml_test (id) select * from y" % db, 1, 0)
- self._validate_dml_stmt(\
+ self._validate_dml_stmt(vector,
"with y as (values(7)) insert into %s.dml_test (id) select * from y" % db, 0, 1)
- self._validate_dml_stmt(\
+ self._validate_dml_stmt(vector,
"with y as (values(7)) upsert into %s.dml_test (id) select * from y" % db, 1, 0)
- def test_missing_query_file(self):
- result = run_impala_shell_cmd('-f nonexistent.sql', expect_success=False)
+ def test_missing_query_file(self, vector):
+ result = run_impala_shell_cmd(vector, ['-f', 'nonexistent.sql'], expect_success=False)
assert "Could not open file 'nonexistent.sql'" in result.stderr
- def _validate_expected_socket_connected(self, args, sock):
+ def _validate_expected_socket_connected(self, vector, args, sock):
# Building an one-off shell command instead of using Util::ImpalaShell since we need
# to customize the impala daemon socket.
- shell_cmd = "%s/bin/impala-shell.sh" % (os.environ['IMPALA_HOME'])
+ shell_cmd = ["{0}/bin/impala-shell.sh".format(os.environ['IMPALA_HOME'])]
expected_output = "PingImpalaService"
with open(os.devnull, 'w') as devnull:
try:
- impala_shell = Popen(shlex.split("%s %s" % (shell_cmd, args, )), stdout=devnull,
- stderr=devnull)
+ connection = None
+ impala_shell = Popen(shell_cmd + args, stdout=devnull, stderr=devnull)
connection, client_address = sock.accept()
data = connection.recv(1024)
assert expected_output in data
@@ -705,7 +722,7 @@ class TestImpalaShell(ImpalaTestSuite):
if connection is not None:
connection.close()
- def test_socket_opening(self):
+ def test_socket_opening(self, vector):
''' Tests that impala-shell will always open a socket against
the host[:port] specified by the -i option with or without the
-b option '''
@@ -716,28 +733,28 @@ class TestImpalaShell(ImpalaTestSuite):
s.listen(1)
test_impalad_port = s.getsockname()[1]
load_balancer_fqdn = "my-load-balancer.local"
- args1 = "-i localhost:%d" % (test_impalad_port,)
- args2 = "%s -b %s" % (args1, load_balancer_fqdn,)
+ args1 = ["-i", "localhost:{0}".format(test_impalad_port)]
+ args2 = args1 + ["-b", load_balancer_fqdn]
# Verify that impala-shell tries to create a socket against the host:port
# combination specified by -i when -b is not used
- self._validate_expected_socket_connected(args1, s)
+ self._validate_expected_socket_connected(vector, args1, s)
# Verify that impala-shell tries to create a socket against the host:port
# combination specified by -i when -b is used
- self._validate_expected_socket_connected(args2, s)
+ self._validate_expected_socket_connected(vector, args2, s)
finally:
s.close()
- def test_malformed_query(self):
+ def test_malformed_query(self, vector):
"""Test that malformed queries are handled by the commandline shell"""
- args = " -q \"with foo as (select bar from temp where temp.a='\""
- result = run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'with foo as (select bar from temp where temp.a=\'"']
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
assert "Encountered: EOF" in result.stderr
- args = "-q \"with v as (select 1) \;\""
- result = run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'with v as (select 1) \;"']
+ result = run_impala_shell_cmd(vector, args, expect_success=False)
assert "Encountered: Unexpected character" in result.stderr
- def test_large_sql(self, unique_database):
+ def test_large_sql(self, vector, unique_database):
# In this test, we are only interested in the performance of Impala shell and not
# the performance of Impala in general. So, this test will execute a large query
# from a non-existent table since this will make the query execution time negligible.
@@ -754,9 +771,9 @@ class TestImpalaShell(ImpalaTestSuite):
os.close(sql_file)
try:
- args = "-q -f {0} -d {1}".format(sql_path, unique_database)
+ args = ['-q', '-f', sql_path, '-d', unique_database]
start_time = time()
- run_impala_shell_cmd(args, False)
+ run_impala_shell_cmd(vector, args, False)
end_time = time()
time_limit_s = 10
actual_time_s = end_time - start_time
@@ -768,7 +785,7 @@ class TestImpalaShell(ImpalaTestSuite):
@pytest.mark.skipif(pytest.config.option.testing_remote_cluster,
reason='Test assumes a minicluster.')
- def test_default_timezone(self):
+ def test_default_timezone(self, vector):
"""Test that the default TIMEZONE query option is a valid timezone.
It would be nice to check that the default timezone is the system's timezone,
@@ -778,11 +795,11 @@ class TestImpalaShell(ImpalaTestSuite):
cluster is platform specific, but there's no guarantee the local machine
is the same OS, and the assert fails if there's a mismatch.
"""
- result_set = run_impala_shell_cmd('-q "set;"')
+ result_set = run_impala_shell_cmd(vector, ['-q', 'set;'])
tzname = find_query_option("TIMEZONE", result_set.stdout)
assert os.path.isfile("/usr/share/zoneinfo/" + tzname)
- def test_find_query_option(self):
+ def test_find_query_option(self, vector):
"""Test utility function find_query_option()."""
test_input = """
not_an_option
@@ -801,7 +818,7 @@ class TestImpalaShell(ImpalaTestSuite):
with pytest.raises(AssertionError):
find_query_option("not_an_option", test_input)
- def test_impala_shell_timeout(self):
+ def test_impala_shell_timeout(self, vector):
"""Tests that impala shell times out during connect.
This creates a random listening socket and we try to connect to this
socket through the impala-shell. The impala-shell should timeout and not hang
@@ -812,11 +829,67 @@ class TestImpalaShell(ImpalaTestSuite):
# maximum number of queued connections on this socket is 1.
s.listen(1)
test_port = s.getsockname()[1]
- args = '-q "select foo; select bar;" --ssl -t 2000 -i localhost:%d' % (test_port)
- run_impala_shell_cmd(args, expect_success=False)
+ args = ['-q', 'select foo; select bar;', '--ssl', '-t', '2000', '-i',
+ 'localhost:%d' % (test_port)]
+ run_impala_shell_cmd(vector, args, expect_success=False)
- def test_client_identifier(self):
+ def test_client_identifier(self, vector):
"""Confirms that a version string is passed along."""
- args = "--query 'select 0; profile'"
- result = run_impala_shell_cmd(args)
+ args = ['--query', 'select 0; profile']
+ result = run_impala_shell_cmd(vector, args)
assert 'client_identifier=impala shell' in result.stdout.lower()
+
+ def test_default_port(self, vector):
+ """Ensure that we can run when -i does not specify a port."""
+ args = ['-q', DEFAULT_QUERY, '-i', IMPALAD_HS2_HOST_PORT.split(":")[0]]
+ run_impala_shell_cmd(vector, args)
+
+ def test_type_formatting(self, vector):
+ """Test formatting of data types that should be identical between HS2 and beeswax,
+ i.e. excluding floating point values which are tested in test_float_formatting."""
+ # Query covers bool, all int types, string, timestamp, date, various decimal types,
+ # CHAR (including a value with padding) and VARCHAR.
+ query = """select bool_col, tinyint_col, smallint_col, int_col, bigint_col,
+ string_col, timestamp_col, date_col, dt.c1, dt.c2, dt.c3,
+ ct.cs, ct.vc
+ from functional.alltypestiny att, functional.date_tbl dtbl,
+ functional.decimal_tiny dt, functional.chars_tiny ct
+ where att.id = 1 and dtbl.id_col = 1 and dt.c1 = 2.2220 and ct.vc = '3ccc'
+ """
+ result = run_impala_shell_cmd(vector, ['-q', query, '-B'])
+ assert("false\t1\t1\t1\t10\t1\t2009-01-01 00:01:00\t0001-12-31\t2.2220\t124.44440"
+ "\t0.0\t3aaa \t3ccc" in result.stdout), result.stdout
+
+ def test_float_formatting(self, vector):
+ """Test that rounding of float types is as expected. Includes some floating point
+ values that can be printed in multiple valid ways. Includes additional expressions
+ to confirm that the output of ROUND() is a DOUBLE and that a plain FLOAT is
+ formatted correctly."""
+ query = """select typeof(round(cast(8.072 as double), 3)), cast(0.5 as float),
+ round(cast(8.072 as double), 3), round(cast(8 as double), 3),
+ round(cast(8.0719999999 as double),3),
+ round(cast(8.072 as double), 0), round(8.072, 4)"""
+ result = run_impala_shell_cmd(vector, ['-q', query, '-B'])
+ # Note that Beeswax formats results differently (i.e. the "fix" for IMPALA-266 stopped
+ # working for Beeswax at some point.
+ assert ("DOUBLE\t0.5\t8.071999999999999\t8\t8.071999999999999\t8\t8.072"
+ in result.stdout)
+
+ def test_bool_display(self, vector):
+ """Test that boolean values are displayed correctly."""
+ query = "select true a, false b"
+ result = run_impala_shell_cmd(vector, ['-q', query])
+ assert "| a | b |" in result.stdout, result.stdout
+ assert "| true | false |" in result.stdout, result.stdout
+
+ def test_null_values(self, vector):
+ """Test that null values are displayed correctly."""
+ query = """select id, int_col, double_col
+ from functional_parquet.alltypesagg where id < 5 order by id"""
+ result = run_impala_shell_cmd(vector, ['-q', query, '-B'])
+ assert "0\tNULL\tNULL" in result.stdout, result.stdout
+ assert "0\tNULL\tNULL" in result.stdout, result.stdout
+ assert "1\t1\t10.1" in result.stdout, result.stdout
+ assert "2\t2\t20.2" in result.stdout, result.stdout
+ assert "3\t3\t30.3" in result.stdout, result.stdout
+ assert "4\t4\t40.4" in result.stdout, result.stdout
diff --git a/tests/shell/test_shell_interactive.py b/tests/shell/test_shell_interactive.py
index 4ee8c61..68fdd83 100755
--- a/tests/shell/test_shell_interactive.py
+++ b/tests/shell/test_shell_interactive.py
@@ -35,14 +35,16 @@ from shell.impala_shell import ImpalaShell as ImpalaShellClass
from tempfile import NamedTemporaryFile
from tests.common.impala_service import ImpaladService
+from tests.common.impala_test_suite import ImpalaTestSuite
from tests.common.skip import SkipIfLocal
-from util import assert_var_substitution, ImpalaShell
+from tests.common.test_dimensions import create_beeswax_dimension
+from util import (assert_var_substitution, ImpalaShell, get_impalad_port,
+ get_shell_cmd, get_open_sessions_metric)
-SHELL_CMD = "%s/bin/impala-shell.sh" % os.environ['IMPALA_HOME']
QUERY_FILE_PATH = os.path.join(os.environ['IMPALA_HOME'], 'tests', 'shell')
# Regex to match the interactive shell prompt that is expected after each command.
-PROMPT_REGEX = r'\[[^:]+:2100[0-9]\]'
+PROMPT_REGEX = r'\[[^:]+:210[0-9][0-9]\]'
@pytest.fixture
@@ -65,40 +67,55 @@ def tmp_history_file(request):
return tmp.name
-class TestImpalaShellInteractive(object):
+class TestImpalaShellInteractive(ImpalaTestSuite):
"""Test the impala shell interactively"""
- def _expect_with_cmd(self, proc, cmd, expectations=(), db="default"):
+ @classmethod
+ def get_workload(self):
+ return 'functional-query'
+
+ @classmethod
+ def add_test_dimensions(cls):
+ cls.ImpalaTestMatrix.add_dimension(create_beeswax_dimension())
+
+ def _expect_with_cmd(self, proc, cmd, vector, expectations=(), db="default"):
"""Executes a command on the expect process instance and verifies a set of
assertions defined by the expectations."""
proc.sendline(cmd + ";")
- proc.expect(":21000] {db}>".format(db=db))
+ proc.expect(":{0}] {1}>".format(get_impalad_port(vector), db))
if not expectations: return
for e in expectations:
assert e in proc.before
- def test_local_shell_options(self):
+ def test_local_shell_options(self, vector):
"""Test that setting the local shell options works"""
- proc = pexpect.spawn(SHELL_CMD)
- proc.expect(":21000] default>")
- self._expect_with_cmd(proc, "set", ("LIVE_PROGRESS: False", "LIVE_SUMMARY: False"))
- self._expect_with_cmd(proc, "set live_progress=true")
- self._expect_with_cmd(proc, "set", ("LIVE_PROGRESS: True", "LIVE_SUMMARY: False"))
- self._expect_with_cmd(proc, "set live_summary=1")
- self._expect_with_cmd(proc, "set", ("LIVE_PROGRESS: True", "LIVE_SUMMARY: True"))
- self._expect_with_cmd(proc, "set", ("WRITE_DELIMITED: False", "VERBOSE: True"))
- self._expect_with_cmd(proc, "set", ("DELIMITER: \\t", "OUTPUT_FILE: None"))
- self._expect_with_cmd(proc, "set write_delimited=true")
- self._expect_with_cmd(proc, "set", ("WRITE_DELIMITED: True", "VERBOSE: True"))
- self._expect_with_cmd(proc, "set DELIMITER=,")
- self._expect_with_cmd(proc, "set", ("DELIMITER: ,", "OUTPUT_FILE: None"))
- self._expect_with_cmd(proc, "set output_file=/tmp/clmn.txt")
- self._expect_with_cmd(proc, "set", ("DELIMITER: ,", "OUTPUT_FILE: /tmp/clmn.txt"))
+ shell_cmd = get_shell_cmd(vector)
+ proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:])
+ proc.expect(":{0}] default>".format(get_impalad_port(vector)))
+ self._expect_with_cmd(proc, "set", vector,
+ ("LIVE_PROGRESS: False", "LIVE_SUMMARY: False"))
+ self._expect_with_cmd(proc, "set live_progress=true", vector)
+ self._expect_with_cmd(proc, "set", vector,
+ ("LIVE_PROGRESS: True", "LIVE_SUMMARY: False"))
+ self._expect_with_cmd(proc, "set live_summary=1", vector)
+ self._expect_with_cmd(proc, "set", vector,
+ ("LIVE_PROGRESS: True", "LIVE_SUMMARY: True"))
+ self._expect_with_cmd(proc, "set", vector,
+ ("WRITE_DELIMITED: False", "VERBOSE: True"))
+ self._expect_with_cmd(proc, "set", vector,
+ ("DELIMITER: \\t", "OUTPUT_FILE: None"))
+ self._expect_with_cmd(proc, "set write_delimited=true", vector)
+ self._expect_with_cmd(proc, "set", vector, ("WRITE_DELIMITED: True", "VERBOSE: True"))
+ self._expect_with_cmd(proc, "set DELIMITER=,", vector)
+ self._expect_with_cmd(proc, "set", vector, ("DELIMITER: ,", "OUTPUT_FILE: None"))
+ self._expect_with_cmd(proc, "set output_file=/tmp/clmn.txt", vector)
+ self._expect_with_cmd(proc, "set", vector,
+ ("DELIMITER: ,", "OUTPUT_FILE: /tmp/clmn.txt"))
@pytest.mark.execute_serially
- def test_write_delimited(self):
+ def test_write_delimited(self, vector):
"""Test output rows in delimited mode"""
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd("use tpch")
p.send_cmd("set write_delimited=true")
p.send_cmd("select * from nation")
@@ -107,9 +124,9 @@ class TestImpalaShellInteractive(object):
assert "21\tVIETNAM\t2" in result.stdout
@pytest.mark.execute_serially
- def test_change_delimiter(self):
+ def test_change_delimiter(self, vector):
"""Test change output delimiter if delimited mode is enabled"""
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd("use tpch")
p.send_cmd("set write_delimited=true")
p.send_cmd("set delimiter=,")
@@ -118,10 +135,10 @@ class TestImpalaShellInteractive(object):
assert "21,VIETNAM,2" in result.stdout
@pytest.mark.execute_serially
- def test_print_to_file(self):
+ def test_print_to_file(self, vector):
"""Test print to output file and unset"""
# test print to file
- p1 = ImpalaShell()
+ p1 = ImpalaShell(vector)
p1.send_cmd("use tpch")
local_file = NamedTemporaryFile(delete=True)
p1.send_cmd("set output_file=%s" % local_file.name)
@@ -133,7 +150,7 @@ class TestImpalaShellInteractive(object):
result = fi.read()
assert "VIETNAM" in result
# test unset to print back to stdout
- p2 = ImpalaShell()
+ p2 = ImpalaShell(vector)
p2.send_cmd("use tpch")
p2.send_cmd("set output_file=%s" % local_file.name)
p2.send_cmd("unset output_file")
@@ -141,38 +158,39 @@ class TestImpalaShellInteractive(object):
result = p2.get_result()
assert "VIETNAM" in result.stdout
- def test_compute_stats_with_live_progress_options(self):
+ def test_compute_stats_with_live_progress_options(self, vector, unique_database):
"""Test that setting LIVE_PROGRESS options won't cause COMPUTE STATS query fail"""
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd("set live_progress=True")
p.send_cmd("set live_summary=True")
- p.send_cmd('create table test_live_progress_option(col int);')
+ table = "{0}.live_progress_option".format(unique_database)
+ p.send_cmd('create table {0}(col int);'.format(table))
try:
- p.send_cmd('compute stats test_live_progress_option;')
+ p.send_cmd('compute stats {0};'.format(table))
finally:
- p.send_cmd('drop table if exists test_live_progress_option;')
+ p.send_cmd('drop table if exists {0};'.format(table))
result = p.get_result()
assert "Updated 1 partition(s) and 1 column(s)" in result.stdout
- def test_escaped_quotes(self):
+ def test_escaped_quotes(self, vector):
"""Test escaping quotes"""
# test escaped quotes outside of quotes
- result = run_impala_shell_interactive("select \\'bc';")
+ result = run_impala_shell_interactive(vector, "select \\'bc';")
assert "Unexpected character" in result.stderr
- result = run_impala_shell_interactive("select \\\"bc\";")
+ result = run_impala_shell_interactive(vector, "select \\\"bc\";")
assert "Unexpected character" in result.stderr
# test escaped quotes within quotes
- result = run_impala_shell_interactive("select 'ab\\'c';")
+ result = run_impala_shell_interactive(vector, "select 'ab\\'c';")
assert "Fetched 1 row(s)" in result.stderr
- result = run_impala_shell_interactive("select \"ab\\\"c\";")
+ result = run_impala_shell_interactive(vector, "select \"ab\\\"c\";")
assert "Fetched 1 row(s)" in result.stderr
@pytest.mark.execute_serially
- def test_cancellation(self):
+ def test_cancellation(self, vector):
impalad = ImpaladService(socket.getfqdn())
assert impalad.wait_for_num_in_flight_queries(0)
command = "select sleep(10000);"
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd(command)
sleep(3)
os.kill(p.pid(), signal.SIGINT)
@@ -180,85 +198,93 @@ class TestImpalaShellInteractive(object):
assert "Cancelled" not in result.stderr
assert impalad.wait_for_num_in_flight_queries(0)
- p = ImpalaShell()
+ p = ImpalaShell(vector)
sleep(3)
os.kill(p.pid(), signal.SIGINT)
result = p.get_result()
assert "^C" in result.stderr
- def test_unicode_input(self):
+ def test_unicode_input(self, vector):
"Test queries containing non-ascii input"
# test a unicode query spanning multiple lines
unicode_text = u'\ufffd'
args = "select '%s'\n;" % unicode_text.encode('utf-8')
- result = run_impala_shell_interactive(args)
+ result = run_impala_shell_interactive(vector, args)
assert "Fetched 1 row(s)" in result.stderr
- def test_welcome_string(self):
+ def test_welcome_string(self, vector):
"""Test that the shell's welcome message is only printed once
when the shell is started. Ensure it is not reprinted on errors.
Regression test for IMPALA-1153
"""
- result = run_impala_shell_interactive('asdf;')
+ result = run_impala_shell_interactive(vector, 'asdf;')
assert result.stdout.count("Welcome to the Impala shell") == 1
- result = run_impala_shell_interactive('select * from non_existent_table;')
+ result = run_impala_shell_interactive(vector, 'select * from non_existent_table;')
assert result.stdout.count("Welcome to the Impala shell") == 1
- def test_disconnected_shell(self):
+ def test_disconnected_shell(self, vector):
"""Test that the shell presents a disconnected prompt if it can't connect
"""
- result = run_impala_shell_interactive('asdf;', shell_args='-i foo',
+ result = run_impala_shell_interactive(vector, 'asdf;', shell_args=['-ifoo'],
wait_until_connected=False)
- assert ImpalaShellClass.DISCONNECTED_PROMPT in result.stdout
+ assert ImpalaShellClass.DISCONNECTED_PROMPT in result.stdout, result.stderr
- def test_bash_cmd_timing(self):
+ def test_bash_cmd_timing(self, vector):
"""Test existence of time output in bash commands run from shell"""
- args = "! ls;"
- result = run_impala_shell_interactive(args)
+ args = ["! ls;"]
+ result = run_impala_shell_interactive(vector, args)
assert "Executed in" in result.stderr
@SkipIfLocal.multiple_impalad
@pytest.mark.execute_serially
- def test_reconnect(self):
+ def test_reconnect(self, vector):
"""Regression Test for IMPALA-1235
Verifies that a connect command by the user is honoured.
"""
+ # Disconnect existing clients so there are no open sessions.
+ self.client.close()
+ self.hs2_client.close()
def wait_for_num_open_sessions(impala_service, num, err):
"""Helper method to wait for the number of open sessions to reach 'num'."""
- assert impala_service.wait_for_metric_value(
- 'impala-server.num-open-beeswax-sessions', num) == num, err
+ metric_name = get_open_sessions_metric(vector)
+ assert impala_service.wait_for_metric_value(metric_name, num) == num, err
hostname = socket.getfqdn()
initial_impala_service = ImpaladService(hostname)
target_impala_service = ImpaladService(hostname, webserver_port=25001,
- beeswax_port=21001, be_port=22001)
+ beeswax_port=21001, be_port=22001, hs2_port=21051)
+ if vector.get_value("protocol") == "hs2":
+ target_port = 21051
+ else:
+ target_port = 21001
# This test is running serially, so there shouldn't be any open sessions, but wait
# here in case a session from a previous test hasn't been fully closed yet.
- wait_for_num_open_sessions(
- initial_impala_service, 0, "21000 should not have any remaining open sessions.")
- wait_for_num_open_sessions(
- target_impala_service, 0, "21001 should not have any remaining open sessions.")
- # Connect to localhost:21000 (default)
- p = ImpalaShell()
+ wait_for_num_open_sessions(initial_impala_service, 0,
+ "first impalad should not have any remaining open sessions.")
+ wait_for_num_open_sessions(target_impala_service, 0,
+ "second impalad should not have any remaining open sessions.")
+ # Connect to the first impalad
+ p = ImpalaShell(vector)
- # Make sure we're connected <hostname>:21000
- wait_for_num_open_sessions(
- initial_impala_service, 1, "Not connected to %s:21000" % hostname)
- p.send_cmd("connect %s:21001" % hostname)
+ # Make sure we're connected <hostname>:<port>
+ wait_for_num_open_sessions(initial_impala_service, 1,
+ "Not connected to %s:%d" % (hostname, get_impalad_port(vector)))
+ p.send_cmd("connect %s:%d" % (hostname, target_port))
# The number of sessions on the target impalad should have been incremented.
wait_for_num_open_sessions(
- target_impala_service, 1, "Not connected to %s:21001" % hostname)
- assert "[%s:21001] default>" % hostname in p.get_result().stdout
+ target_impala_service, 1, "Not connected to %s:%d" % (hostname, target_port))
+ assert "[%s:%d] default>" % (hostname, target_port) in p.get_result().stdout
# The number of sessions on the initial impalad should have been decremented.
wait_for_num_open_sessions(initial_impala_service, 0,
- "Connection to %s:21000 should have been closed" % hostname)
+ "Connection to %s:%d should have been closed" % (
+ hostname, get_impalad_port(vector)))
@pytest.mark.execute_serially
- def test_ddl_queries_are_closed(self):
+ def test_ddl_queries_are_closed(self, vector):
"""Regression test for IMPALA-1317
The shell does not call close() for alter, use and drop queries, leaving them in
@@ -273,7 +299,7 @@ class TestImpalaShellInteractive(object):
NUM_QUERIES = 'impala-server.num-queries'
impalad = ImpaladService(socket.getfqdn())
- p = ImpalaShell()
+ p = ImpalaShell(vector)
try:
start_num_queries = impalad.get_metric_value(NUM_QUERIES)
p.send_cmd('create database if not exists %s' % TMP_DB)
@@ -288,17 +314,19 @@ class TestImpalaShellInteractive(object):
impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 5)
assert impalad.wait_for_num_in_flight_queries(0), MSG % 'drop'
finally:
- run_impala_shell_interactive("drop table if exists %s.%s;" % (TMP_DB, TMP_TBL))
- run_impala_shell_interactive("drop database if exists foo;")
+ run_impala_shell_interactive(vector, "drop table if exists %s.%s;" % (
+ TMP_DB, TMP_TBL))
+ run_impala_shell_interactive(vector, "drop database if exists foo;")
- def test_multiline_queries_in_history(self, tmp_history_file):
+ def test_multiline_queries_in_history(self, vector, tmp_history_file):
"""Test to ensure that multiline queries with comments are preserved in history
Ensure that multiline queries are preserved when they're read back from history.
Additionally, also test that comments are preserved.
"""
# readline gets its input from tty, so using stdin does not work.
- child_proc = pexpect.spawn(SHELL_CMD)
+ shell_cmd = get_shell_cmd(vector)
+ child_proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:])
# List of (input query, expected text in output).
# The expected output is usually the same as the input with a number prefix, except
# where the shell strips newlines before a semicolon.
@@ -314,14 +342,14 @@ class TestImpalaShellInteractive(object):
child_proc.expect("Fetched 1 row\(s\) in [0-9]+\.?[0-9]*s")
child_proc.expect(PROMPT_REGEX)
child_proc.sendline('quit;')
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd('history')
result = p.get_result()
for _, history_entry in queries:
assert history_entry in result.stderr, "'%s' not in '%s'" % (history_entry,
result.stderr)
- def test_history_file_option(self, tmp_history_file):
+ def test_history_file_option(self, vector, tmp_history_file):
"""
Setting the 'tmp_history_file' fixture above means that the IMPALA_HISTFILE
environment will be overridden. Here we override that environment by passing
@@ -329,48 +357,51 @@ class TestImpalaShellInteractive(object):
in the appropriate spot.
"""
with NamedTemporaryFile() as new_hist:
- child_proc = pexpect.spawn(
- SHELL_CMD,
- args=["--history_file=%s" % new_hist.name])
- child_proc.expect(":21000] default>")
- self._expect_with_cmd(child_proc, "select 'hi'", ('hi'))
+ shell_cmd = get_shell_cmd(vector) + ["--history_file=%s" % new_hist.name]
+ child_proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:])
+ child_proc.expect(":{0}] default>".format(get_impalad_port(vector)))
+ self._expect_with_cmd(child_proc, "select 'hi'", vector, ('hi'))
child_proc.sendline('exit;')
child_proc.expect(pexpect.EOF)
history_contents = file(new_hist.name).read()
assert "select 'hi'" in history_contents
- def test_rerun(self, tmp_history_file):
+ def test_rerun(self, vector, tmp_history_file):
"""Smoke test for the 'rerun' command"""
- child_proc = pexpect.spawn(SHELL_CMD)
- child_proc.expect(":21000] default>")
- self._expect_with_cmd(child_proc, "@1", ("Command index out of range"))
- self._expect_with_cmd(child_proc, "rerun -1", ("Command index out of range"))
- self._expect_with_cmd(child_proc, "select 'first_command'", ("first_command"))
- self._expect_with_cmd(child_proc, "rerun 1", ("first_command"))
- self._expect_with_cmd(child_proc, "@ -1", ("first_command"))
- self._expect_with_cmd(child_proc, "select 'second_command'", ("second_command"))
+ shell_cmd = get_shell_cmd(vector)
+ child_proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:])
+ child_proc.expect(":{0}] default>".format(get_impalad_port(vector)))
+ self._expect_with_cmd(child_proc, "@1", vector, ("Command index out of range"))
+ self._expect_with_cmd(child_proc, "rerun -1", vector,
+ ("Command index out of range"))
+ self._expect_with_cmd(child_proc, "select 'first_command'", vector,
+ ("first_command"))
+ self._expect_with_cmd(child_proc, "rerun 1", vector, ("first_command"))
+ self._expect_with_cmd(child_proc, "@ -1", vector, ("first_command"))
+ self._expect_with_cmd(child_proc, "select 'second_command'", vector,
+ ("second_command"))
child_proc.sendline('history;')
- child_proc.expect(":21000] default>")
+ child_proc.expect(":{0}] default>".format(get_impalad_port(vector)))
assert '[1]: select \'first_command\';' in child_proc.before
assert '[2]: select \'second_command\';' in child_proc.before
assert '[3]: history;' in child_proc.before
# Rerunning command should not add an entry into history.
assert '[4]' not in child_proc.before
- self._expect_with_cmd(child_proc, "@0", ("Command index out of range"))
- self._expect_with_cmd(child_proc, "rerun 4", ("Command index out of range"))
- self._expect_with_cmd(child_proc, "@-4", ("Command index out of range"))
- self._expect_with_cmd(child_proc, " @ 3 ", ("second_command"))
- self._expect_with_cmd(child_proc, "@-3", ("first_command"))
- self._expect_with_cmd(child_proc, "@",
+ self._expect_with_cmd(child_proc, "@0", vector, ("Command index out of range"))
+ self._expect_with_cmd(child_proc, "rerun 4", vector, ("Command index out of range"))
+ self._expect_with_cmd(child_proc, "@-4", vector, ("Command index out of range"))
+ self._expect_with_cmd(child_proc, " @ 3 ", vector, ("second_command"))
+ self._expect_with_cmd(child_proc, "@-3", vector, ("first_command"))
+ self._expect_with_cmd(child_proc, "@", vector,
("Command index to be rerun must be an integer."))
- self._expect_with_cmd(child_proc, "@1foo",
+ self._expect_with_cmd(child_proc, "@1foo", vector,
("Command index to be rerun must be an integer."))
- self._expect_with_cmd(child_proc, "@1 2",
+ self._expect_with_cmd(child_proc, "@1 2", vector,
("Command index to be rerun must be an integer."))
- self._expect_with_cmd(child_proc, "rerun1", ("Syntax error"))
+ self._expect_with_cmd(child_proc, "rerun1", vector, ("Syntax error"))
child_proc.sendline('quit;')
- def test_tip(self):
+ def test_tip(self, vector):
"""Smoke test for the TIP command"""
# Temporarily add impala_shell module to path to get at TIPS list for verification
sys.path.append("%s/shell/" % os.environ['IMPALA_HOME'])
@@ -378,35 +409,36 @@ class TestImpalaShellInteractive(object):
import impala_shell
finally:
sys.path = sys.path[:-1]
- result = run_impala_shell_interactive("tip;")
+ result = run_impala_shell_interactive(vector, "tip;")
for t in impala_shell.TIPS:
if t in result.stderr: return
assert False, "No tip found in output %s" % result.stderr
- def test_var_substitution(self):
+ def test_var_substitution(self, vector):
cmds = open(os.path.join(QUERY_FILE_PATH, 'test_var_substitution.sql')).read()
- args = '''--var=foo=123 --var=BAR=456 --delimited "--output_delimiter= " '''
- result = run_impala_shell_interactive(cmds, shell_args=args)
+ args = ["--var=foo=123", "--var=BAR=456", "--delimited", "--output_delimiter= "]
+ result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert_var_substitution(result)
- def test_query_option_configuration(self):
+ def test_query_option_configuration(self, vector):
rcfile_path = os.path.join(QUERY_FILE_PATH, 'impalarc_with_query_options')
- args = '-Q MT_dop=1 --query_option=MAX_ERRORS=200 --config_file="%s"' % rcfile_path
+ args = ['-Q', 'MT_dop=1', '--query_option=MAX_ERRORS=200',
+ '--config_file=%s' % rcfile_path]
cmds = "set all;"
- result = run_impala_shell_interactive(cmds, shell_args=args)
+ result = run_impala_shell_interactive(vector, cmds, shell_args=args)
assert "\tMT_DOP: 1" in result.stdout
assert "\tMAX_ERRORS: 200" in result.stdout
assert "\tEXPLAIN_LEVEL: 2" in result.stdout
assert "INVALID_QUERY_OPTION is not supported for the impalad being connected to, "\
"ignoring." in result.stdout
- def test_source_file(self):
+ def test_source_file(self, vector):
cwd = os.getcwd()
try:
# Change working dir so that SOURCE command in shell.cmds can find shell2.cmds.
os.chdir("%s/tests/shell/" % os.environ['IMPALA_HOME'])
# IMPALA-5416: Test that a command following 'source' won't be run twice.
- result = run_impala_shell_interactive("source shell.cmds;select \"second "
+ result = run_impala_shell_interactive(vector, "source shell.cmds;select \"second "
"command\";")
assert "Query: USE FUNCTIONAL" in result.stderr
assert "Query: SHOW TABLES" in result.stderr
@@ -416,57 +448,60 @@ class TestImpalaShellInteractive(object):
assert "version()" in result.stdout
assert len(re.findall("'second command'", result.stdout)) == 1
# IMPALA-5416: Test that two source commands on a line won't crash the shell.
- result = run_impala_shell_interactive("source shell.cmds;source shell.cmds;")
+ result = run_impala_shell_interactive(
+ vector, "source shell.cmds;source shell.cmds;")
assert len(re.findall("version\(\)", result.stdout)) == 2
finally:
os.chdir(cwd)
- def test_source_file_with_errors(self):
+ def test_source_file_with_errors(self, vector):
full_path = "%s/tests/shell/shell_error.cmds" % os.environ['IMPALA_HOME']
- result = run_impala_shell_interactive("source %s;" % full_path)
+ result = run_impala_shell_interactive(vector, "source %s;" % full_path)
assert "Could not execute command: USE UNKNOWN_DATABASE" in result.stderr
assert "Query: USE FUNCTIONAL" not in result.stderr
- result = run_impala_shell_interactive("source %s;" % full_path, '-c')
- assert "Could not execute command: USE UNKNOWN_DATABASE" in result.stderr
- assert "Query: USE FUNCTIONAL" in result.stderr
- assert "Query: SHOW TABLES" in result.stderr
- assert "alltypes" in result.stdout
+ result = run_impala_shell_interactive(vector, "source %s;" % full_path, ['-c'])
+ assert "Could not execute command: USE UNKNOWN_DATABASE" in result.stderr,\
+ result.stderr
+ assert "Query: USE FUNCTIONAL" in result.stderr, result.stderr
+ assert "Query: SHOW TABLES" in result.stderr, result.stderr
+ assert "alltypes" in result.stdout, result.stdout
- def test_source_missing_file(self):
+ def test_source_missing_file(self, vector):
full_path = "%s/tests/shell/doesntexist.cmds" % os.environ['IMPALA_HOME']
- result = run_impala_shell_interactive("source %s;" % full_path)
+ result = run_impala_shell_interactive(vector, "source %s;" % full_path)
assert "No such file or directory" in result.stderr
- def test_zero_row_fetch(self):
+ def test_zero_row_fetch(self, vector):
# IMPALA-4418: DROP and USE are generally exceptional statements where
# the client does not fetch. For statements returning 0 rows we do not
# want an empty line in stdout.
- result = run_impala_shell_interactive("-- foo \n use default;")
+ result = run_impala_shell_interactive(vector, "-- foo \n use default;")
assert re.search('> \[', result.stdout)
- result = run_impala_shell_interactive("select * from functional.alltypes limit 0;")
+ result = run_impala_shell_interactive(vector,
+ "select * from functional.alltypes limit 0;")
assert "Fetched 0 row(s)" in result.stderr
assert re.search('> \[', result.stdout)
- def test_set_and_set_all(self):
+ def test_set_and_set_all(self, vector):
"""IMPALA-2181. Tests the outputs of SET and SET ALL commands. SET should contain the
REGULAR and ADVANCED options only. SET ALL should contain all the options grouped by
display level."""
- shell1 = ImpalaShell()
+ shell1 = ImpalaShell(vector)
shell1.send_cmd("set")
result = shell1.get_result()
assert "Query options (defaults shown in []):" in result.stdout
assert "ABORT_ON_ERROR" in result.stdout
assert "Advanced Query Options:" in result.stdout
assert "APPX_COUNT_DISTINCT" in result.stdout
- assert "SUPPORT_START_OVER" in result.stdout
+ assert vector.get_value("protocol") == "hs2" or "SUPPORT_START_OVER" in result.stdout
# Development, deprecated and removed options should not be shown.
# Note: there are currently no deprecated options
assert "Development Query Options:" not in result.stdout
assert "DEBUG_ACTION" not in result.stdout # Development option.
assert "MAX_IO_BUFFERS" not in result.stdout # Removed option.
- shell2 = ImpalaShell()
+ shell2 = ImpalaShell(vector)
shell2.send_cmd("set all")
result = shell2.get_result()
assert "Query options (defaults shown in []):" in result.stdout
@@ -480,41 +515,41 @@ class TestImpalaShellInteractive(object):
development_part = result.stdout[development_part_start_idx:deprecated_part_start_idx]
assert "ABORT_ON_ERROR" in result.stdout[:advanced_part_start_idx]
assert "APPX_COUNT_DISTINCT" in advanced_part
- assert "SUPPORT_START_OVER" in advanced_part
+ assert vector.get_value("protocol") == "hs2" or "SUPPORT_START_OVER" in advanced_part
assert "DEBUG_ACTION" in development_part
# Removed options should not be shown.
assert "MAX_IO_BUFFERS" not in result.stdout
- def check_command_case_sensitivity(self, command, expected):
- shell = ImpalaShell()
+ def check_command_case_sensitivity(self, vector, command, expected):
+ shell = ImpalaShell(vector)
shell.send_cmd(command)
assert expected in shell.get_result().stderr
- def test_unexpected_conversion_for_literal_string_to_lowercase(self):
+ def test_unexpected_conversion_for_literal_string_to_lowercase(self, vector):
# IMPALA-4664: Impala shell can accidentally convert certain literal
# strings to lowercase. Impala shell splits each command into tokens
# and then converts the first token to lowercase to figure out how it
# should execute the command. The splitting is done by spaces only.
# Thus, if the user types a TAB after the SELECT, the first token after
# the split becomes the SELECT plus whatever comes after it.
- result = run_impala_shell_interactive("select'MUST_HAVE_UPPER_STRING'")
+ result = run_impala_shell_interactive(vector, "select'MUST_HAVE_UPPER_STRING'")
assert re.search('MUST_HAVE_UPPER_STRING', result.stdout)
- result = run_impala_shell_interactive("select\t'MUST_HAVE_UPPER_STRING'")
+ result = run_impala_shell_interactive(vector, "select\t'MUST_HAVE_UPPER_STRING'")
assert re.search('MUST_HAVE_UPPER_STRING', result.stdout)
- result = run_impala_shell_interactive("select\n'MUST_HAVE_UPPER_STRING'")
+ result = run_impala_shell_interactive(vector, "select\n'MUST_HAVE_UPPER_STRING'")
assert re.search('MUST_HAVE_UPPER_STRING', result.stdout)
- def test_case_sensitive_command(self):
+ def test_case_sensitive_command(self, vector):
# IMPALA-2640: Make a given command case-sensitive
cwd = os.getcwd()
try:
- self.check_command_case_sensitivity("sElEcT VERSION()", "Query: sElEcT")
- self.check_command_case_sensitivity("sEt VaR:FoO=bOo", "Variable FOO")
- self.check_command_case_sensitivity("sHoW tables", "Query: sHoW")
+ self.check_command_case_sensitivity(vector, "sElEcT VERSION()", "Query: sElEcT")
+ self.check_command_case_sensitivity(vector, "sEt VaR:FoO=bOo", "Variable FOO")
+ self.check_command_case_sensitivity(vector, "sHoW tables", "Query: sHoW")
# Change working dir so that SOURCE command in shell_case_sensitive.cmds can
# find shell_case_sensitive2.cmds.
os.chdir("%s/tests/shell/" % os.environ['IMPALA_HOME'])
- result = run_impala_shell_interactive(
+ result = run_impala_shell_interactive(vector,
"sOuRcE shell_case_sensitive.cmds; SeLeCt 'second command'")
print result.stderr
assert "Query: uSe FUNCTIONAL" in result.stderr
@@ -527,72 +562,69 @@ class TestImpalaShellInteractive(object):
finally:
os.chdir(cwd)
- def test_line_with_leading_comment(self):
+ def test_line_with_leading_comment(self, vector, unique_database):
# IMPALA-2195: A line with a comment produces incorrect command.
- try:
- run_impala_shell_interactive('drop table if exists leading_comment;')
- run_impala_shell_interactive('create table leading_comment (i int);')
- result = run_impala_shell_interactive('-- comment\n'
- 'insert into leading_comment values(1);')
- assert 'Modified 1 row(s)' in result.stderr
- result = run_impala_shell_interactive('-- comment\n'
- 'select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
- result = run_impala_shell_interactive('--한글\n'
- 'select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
- result = run_impala_shell_interactive('/* 한글 */\n'
- 'select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
- result = run_impala_shell_interactive('/* comment */\n'
- 'select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
-
- result = run_impala_shell_interactive('/* comment1 */\n'
- '-- comment2\n'
- 'select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
-
- result = run_impala_shell_interactive('/* comment1\n'
- 'comment2 */ select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
-
- result = run_impala_shell_interactive('/* select * from leading_comment */ '
- 'select * from leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
-
- result = run_impala_shell_interactive('/* comment */ help use')
- assert 'Executes a USE... query' in result.stdout
-
- result = run_impala_shell_interactive('-- comment\n'
- ' help use;')
- assert 'Executes a USE... query' in result.stdout
-
- result = run_impala_shell_interactive('/* comment1 */\n'
- '-- comment2\n'
- 'desc leading_comment;')
- assert 'Fetched 1 row(s)' in result.stderr
-
- result = run_impala_shell_interactive('/* comment1 */\n'
- '-- comment2\n'
- 'help use;')
- assert 'Executes a USE... query' in result.stdout
- finally:
- run_impala_shell_interactive('drop table if exists leading_comment;')
-
- def test_line_ends_with_comment(self):
+ table = "{0}.leading_comment".format(unique_database)
+ run_impala_shell_interactive(vector, 'create table {0} (i int);'.format(table))
+ result = run_impala_shell_interactive(vector, '-- comment\n'
+ 'insert into {0} values(1);'.format(table))
+ assert 'Modified 1 row(s)' in result.stderr
+ result = run_impala_shell_interactive(vector, '-- comment\n'
+ 'select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+ result = run_impala_shell_interactive(vector, '--한글\n'
+ 'select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+ result = run_impala_shell_interactive(vector, '/* 한글 */\n'
+ 'select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+ result = run_impala_shell_interactive(vector, '/* comment */\n'
+ 'select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive(vector, '/* comment1 */\n'
+ '-- comment2\n'
+ 'select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive(vector, '/* comment1\n'
+ 'comment2 */ select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive(vector, '/* select * from {0} */ '
+ 'select * from {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive(vector, '/* comment */ help use')
+ assert 'Executes a USE... query' in result.stdout
+
+ result = run_impala_shell_interactive(vector, '-- comment\n'
+ ' help use;')
+ assert 'Executes a USE... query' in result.stdout
+
+ result = run_impala_shell_interactive(vector, '/* comment1 */\n'
+ '-- comment2\n'
+ 'desc {0};'.format(table))
+ assert 'Fetched 1 row(s)' in result.stderr
+
+ result = run_impala_shell_interactive(vector, '/* comment1 */\n'
+ '-- comment2\n'
+ 'help use;')
+ assert 'Executes a USE... query' in result.stdout
+
+ def test_line_ends_with_comment(self, vector):
# IMPALA-5269: Test lines that end with a comment.
queries = ['select 1 + 1; --comment',
'select 1 + 1 --comment\n;']
for query in queries:
- result = run_impala_shell_interactive(query)
+ result = run_impala_shell_interactive(vector, query)
assert '| 1 + 1 |' in result.stdout
assert '| 2 |' in result.stdout
queries = ['select \'some string\'; --comment',
'select \'some string\' --comment\n;']
for query in queries:
- result = run_impala_shell_interactive(query)
+ result = run_impala_shell_interactive(vector, query)
assert '| \'some string\' |' in result.stdout
assert '| some string |' in result.stdout
@@ -601,37 +633,37 @@ class TestImpalaShellInteractive(object):
'select "--" -- "--"\n;',
'select \'--\' -- "--"\n;']
for query in queries:
- result = run_impala_shell_interactive(query)
+ result = run_impala_shell_interactive(vector, query)
assert '| \'--\' |' in result.stdout
assert '| -- |' in result.stdout
query = ('select * from (\n' +
'select count(*) from functional.alltypes\n' +
') v; -- Incomplete SQL statement in this line')
- result = run_impala_shell_interactive(query)
+ result = run_impala_shell_interactive(vector, query)
assert '| count(*) |' in result.stdout
query = ('select id from functional.alltypes\n' +
'order by id; /*\n' +
'* Multi-line comment\n' +
'*/')
- result = run_impala_shell_interactive(query)
+ result = run_impala_shell_interactive(vector, query)
assert '| id |' in result.stdout
- def test_fix_infinite_loop(self):
+ def test_fix_infinite_loop(self, vector):
# IMPALA-6337: Fix infinite loop.
- result = run_impala_shell_interactive("select 1 + 1; \"\n;\";")
+ result = run_impala_shell_interactive(vector, "select 1 + 1; \"\n;\";")
assert '| 2 |' in result.stdout
- result = run_impala_shell_interactive("select '1234'\";\n;\n\";")
+ result = run_impala_shell_interactive(vector, "select '1234'\";\n;\n\";")
assert '| 1234 |' in result.stdout
- result = run_impala_shell_interactive("select 1 + 1; \"\n;\"\n;")
+ result = run_impala_shell_interactive(vector, "select 1 + 1; \"\n;\"\n;")
assert '| 2 |' in result.stdout
- result = run_impala_shell_interactive("select '1\\'23\\'4'\";\n;\n\";")
+ result = run_impala_shell_interactive(vector, "select '1\\'23\\'4'\";\n;\n\";")
assert '| 1\'23\'4 |' in result.stdout
- result = run_impala_shell_interactive("select '1\"23\"4'\";\n;\n\";")
+ result = run_impala_shell_interactive(vector, "select '1\"23\"4'\";\n;\n\";")
assert '| 1"23"4 |' in result.stdout
- def test_comment_with_quotes(self):
+ def test_comment_with_quotes(self, vector):
# IMPALA-2751: Comment does not need to have matching quotes
queries = [
"select -- '\n1;",
@@ -645,38 +677,39 @@ class TestImpalaShellInteractive(object):
"with a as (\nselect 1\n-- '\"\n) select * from a",
]
for query in queries:
- result = run_impala_shell_interactive(query)
+ result = run_impala_shell_interactive(vector, query)
assert '| 1 |' in result.stdout
- def test_shell_prompt(self):
- proc = pexpect.spawn(SHELL_CMD)
- proc.expect(":21000] default>")
- self._expect_with_cmd(proc, "use foo", (), 'default')
- self._expect_with_cmd(proc, "use functional", (), 'functional')
- self._expect_with_cmd(proc, "use foo", (), 'functional')
- self._expect_with_cmd(proc, 'use `tpch`', (), 'tpch')
- self._expect_with_cmd(proc, 'use ` tpch `', (), 'tpch')
+ def test_shell_prompt(self, vector):
+ shell_cmd = get_shell_cmd(vector)
+ proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:])
+ proc.expect(":{0}] default>".format(get_impalad_port(vector)))
+ self._expect_with_cmd(proc, "use foo", vector, (), 'default')
+ self._expect_with_cmd(proc, "use functional", vector, (), 'functional')
+ self._expect_with_cmd(proc, "use foo", vector, (), 'functional')
+ self._expect_with_cmd(proc, 'use `tpch`', vector, (), 'tpch')
+ self._expect_with_cmd(proc, 'use ` tpch `', vector, (), 'tpch')
- proc = pexpect.spawn(SHELL_CMD, ['-d', 'functional'])
- proc.expect(":21000] functional>")
- self._expect_with_cmd(proc, "use foo", (), 'functional')
- self._expect_with_cmd(proc, "use tpch", (), 'tpch')
- self._expect_with_cmd(proc, "use foo", (), 'tpch')
+ proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:] + ['-d', 'functional'])
+ proc.expect(":{0}] functional>".format(get_impalad_port(vector)))
+ self._expect_with_cmd(proc, "use foo", vector, (), 'functional')
+ self._expect_with_cmd(proc, "use tpch", vector, (), 'tpch')
+ self._expect_with_cmd(proc, "use foo", vector, (), 'tpch')
- proc = pexpect.spawn(SHELL_CMD, ['-d', ' functional '])
- proc.expect(":21000] functional>")
+ proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:] + ['-d', ' functional '])
+ proc.expect(":{0}] functional>".format(get_impalad_port(vector)))
- proc = pexpect.spawn(SHELL_CMD, ['-d', '` functional `'])
- proc.expect(":21000] functional>")
+ proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:] + ['-d', '` functional `'])
+ proc.expect(":{0}] functional>".format(get_impalad_port(vector)))
# Start an Impala shell with an invalid DB.
- proc = pexpect.spawn(SHELL_CMD, ['-d', 'foo'])
- proc.expect(":21000] default>")
- self._expect_with_cmd(proc, "use foo", (), 'default')
- self._expect_with_cmd(proc, "use functional", (), 'functional')
- self._expect_with_cmd(proc, "use foo", (), 'functional')
+ proc = pexpect.spawn(shell_cmd[0], shell_cmd[1:] + ['-d', 'foo'])
+ proc.expect(":{0}] default>".format(get_impalad_port(vector)))
+ self._expect_with_cmd(proc, "use foo", vector, (), 'default')
+ self._expect_with_cmd(proc, "use functional", vector, (), 'functional')
+ self._expect_with_cmd(proc, "use foo", vector, (), 'functional')
- def test_strip_leading_comment(self):
+ def test_strip_leading_comment(self, vector):
"""Test stripping leading comments from SQL statements"""
assert ('--delete\n', 'select 1') == \
ImpalaShellClass.strip_leading_comment('--delete\nselect 1')
@@ -724,34 +757,35 @@ class TestImpalaShellInteractive(object):
assert (None, 'select 1') == \
ImpalaShellClass.strip_leading_comment('select 1')
- def test_malformed_query(self):
+ def test_malformed_query(self, vector):
"""Test the handling of malformed query without closing quotation"""
- shell = ImpalaShell()
+ shell = ImpalaShell(vector)
query = "with v as (select 1) \nselect foo('\\\\'), ('bar \n;"
shell.send_cmd(query)
result = shell.get_result()
- assert "ERROR: ParseException: Unmatched string literal" in result.stderr
+ assert "ERROR: ParseException: Unmatched string literal" in result.stderr,\
+ result.stderr
- def test_timezone_validation(self):
+ def test_timezone_validation(self, vector):
"""Test that query option TIMEZONE is validated when executing a query.
Query options are not sent to the coordinator immediately, so the error checking
will only happen when running a query.
"""
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd('set timezone=BLA;')
p.send_cmd('select 1;')
results = p.get_result()
assert "Fetched 1 row" not in results.stderr
- assert "ERROR: Errors parsing query options" in results.stderr
- assert "Invalid timezone name 'BLA'" in results.stderr
+ # assert "ERROR: Errors parsing query options" in results.stderr, results.stderr
+ assert "Invalid timezone name 'BLA'" in results.stderr, results.stderr
- def test_with_clause(self):
+ def test_with_clause(self, vector):
# IMPALA-7939: Fix issue where CTE that contains "insert", "upsert", "update", or
# "delete" is categorized as a DML statement.
for keyword in ["insert", "upsert", "update", "delete", "\\'insert\\'",
"\\'upsert\\'", "\\'update\\'", "\\'delete\\'"]:
- p = ImpalaShell()
+ p = ImpalaShell(vector)
p.send_cmd("with foo as "
"(select * from functional.alltypestiny where string_col='%s') "
"select * from foo limit 1" % keyword)
@@ -759,7 +793,8 @@ class TestImpalaShellInteractive(object):
assert "Fetched 0 row" in result.stderr
-def run_impala_shell_interactive(input_lines, shell_args=None, wait_until_connected=True):
+def run_impala_shell_interactive(vector, input_lines, shell_args=None,
+ wait_until_connected=True):
"""Runs a command in the Impala shell interactively."""
# if argument "input_lines" is a string, makes it into a list
if type(input_lines) is str:
@@ -768,7 +803,8 @@ def run_impala_shell_interactive(input_lines, shell_args=None, wait_until_connec
# since piping defaults to ascii
my_env = os.environ
my_env['PYTHONIOENCODING'] = 'utf-8'
- p = ImpalaShell(args=shell_args, env=my_env, wait_until_connected=wait_until_connected)
+ p = ImpalaShell(vector, args=shell_args, env=my_env,
+ wait_until_connected=wait_until_connected)
for line in input_lines:
p.send_cmd(line)
return p.get_result()
diff --git a/tests/shell/util.py b/tests/shell/util.py
index f49cbfe..6c15250 100755
--- a/tests/shell/util.py
+++ b/tests/shell/util.py
@@ -25,10 +25,7 @@ import shlex
import time
from subprocess import Popen, PIPE
-IMPALAD_HOST_PORT_LIST = pytest.config.option.impalad.split(',')
-assert len(IMPALAD_HOST_PORT_LIST) > 0, 'Must specify at least 1 impalad to target'
-IMPALAD = IMPALAD_HOST_PORT_LIST[0]
-SHELL_CMD = "%s/bin/impala-shell.sh -i %s" % (os.environ['IMPALA_HOME'], IMPALAD)
+from tests.common.impala_test_suite import IMPALAD_BEESWAX_HOST_PORT
SHELL_HISTORY_FILE = os.path.expanduser("~/.impalahistory")
def assert_var_substitution(result):
@@ -86,14 +83,14 @@ def assert_pattern(pattern, result, text, message):
assert m and m.group(0) == result, message
-def run_impala_shell_cmd(shell_args, expect_success=True, stdin_input=None,
+def run_impala_shell_cmd(vector, shell_args, expect_success=True, stdin_input=None,
wait_until_connected=True):
"""Runs the Impala shell on the commandline.
'shell_args' is a string which represents the commandline options.
Returns a ImpalaShellResult.
"""
- result = run_impala_shell_cmd_no_expect(shell_args, stdin_input,
+ result = run_impala_shell_cmd_no_expect(vector, shell_args, stdin_input,
expect_success and wait_until_connected)
if expect_success:
assert result.rc == 0, "Cmd %s was expected to succeed: %s" % (shell_args,
@@ -103,7 +100,7 @@ def run_impala_shell_cmd(shell_args, expect_success=True, stdin_input=None,
return result
-def run_impala_shell_cmd_no_expect(shell_args, stdin_input=None,
+def run_impala_shell_cmd_no_expect(vector, shell_args, stdin_input=None,
wait_until_connected=True):
"""Runs the Impala shell on the commandline.
@@ -112,11 +109,36 @@ def run_impala_shell_cmd_no_expect(shell_args, stdin_input=None,
Does not assert based on success or failure of command.
"""
- p = ImpalaShell(shell_args, wait_until_connected=wait_until_connected)
+ p = ImpalaShell(vector, shell_args, wait_until_connected=wait_until_connected)
result = p.get_result(stdin_input)
return result
+def get_impalad_host_port(vector):
+ """Get host and port to connect to based on test vector provided."""
+ protocol = vector.get_value("protocol")
+ assert protocol == 'beeswax', protocol
+ return IMPALAD_BEESWAX_HOST_PORT
+
+
+def get_impalad_port(vector):
+ """Get integer port to connect to based on test vector provided."""
+ return int(get_impalad_host_port(vector).split(":")[1])
+
+
+def get_shell_cmd(vector):
+ """Get the basic shell command to start the shell, given the provided test vector.
+ Returns the command as a list of string arguments."""
+ return [os.path.join(os.environ['IMPALA_HOME'], "bin/impala-shell.sh"),
+ "-i{0}".format(get_impalad_host_port(vector))]
+
+
+def get_open_sessions_metric(vector):
+ """Get the name of the vector that tracks open sessions for the protocol in vector."""
+ protocol = vector.get_value("protocol")
+ assert protocol == 'beeswax', protocol
+ return 'impala-server.num-open-beeswax-sessions'
+
class ImpalaShellResult(object):
def __init__(self):
self.rc = 0
@@ -128,10 +150,10 @@ class ImpalaShell(object):
"""A single instance of the Impala shell. The proces is started when this object is
constructed, and then users should repeatedly call send_cmd(), followed eventually by
get_result() to retrieve the process output. This constructor will wait until
- Impala shell is connected for the specified timeout unless wait_util_connected is
- set to False or --quiet is passed into the args"""
- def __init__(self, args=None, env=None, wait_until_connected=True, timeout=60):
- self.shell_process = self._start_new_shell_process(args, env=env)
+ Impala shell is connected for the specified timeout unless wait_until_connected is
+ set to False or --quiet is passed into the args."""
+ def __init__(self, vector, args=None, env=None, wait_until_connected=True, timeout=60):
+ self.shell_process = self._start_new_shell_process(vector, args, env=env)
# When --quiet option is passed to Impala shell, we should not wait until we see
# "Connected to" because it will never be printed to stderr.
if wait_until_connected and (args is None or "--quiet" not in args):
@@ -179,11 +201,10 @@ class ImpalaShell(object):
result.rc = self.shell_process.returncode
return result
- def _start_new_shell_process(self, args=None, env=None):
+ def _start_new_shell_process(self, vector, args=None, env=None):
"""Starts a shell process and returns the process handle"""
- shell_args = SHELL_CMD
- if args is not None: shell_args = "%s %s" % (SHELL_CMD, args)
- lex = shlex.split(shell_args)
+ cmd = get_shell_cmd(vector)
+ if args is not None: cmd += args
if not env: env = os.environ
- return Popen(lex, shell=False, stdout=PIPE, stdin=PIPE, stderr=PIPE,
+ return Popen(cmd, shell=False, stdout=PIPE, stdin=PIPE, stderr=PIPE,
env=env)