Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rename CrateCmd to CrateShell #257

Merged
merged 3 commits into from Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
75 changes: 40 additions & 35 deletions src/crate/crash/command.py
Expand Up @@ -208,11 +208,11 @@ def _parse_statements(lines):
yield ' '.join(parts)


class CrateCmd(object):
class CrateShell:

def __init__(self,
crate_hosts=['localhost:4200'],
output_writer=None,
connection=None,
error_trace=False,
is_tty=True,
autocomplete=True,
Expand All @@ -222,12 +222,20 @@ def __init__(self,
key_file=None,
ca_cert_file=None,
username=None,
password=None):
self.error_trace = error_trace
self.connection = connection or connect(error_trace=error_trace)
password=None,
timeout=None):
self.connection = connect(crate_hosts,
error_trace=error_trace,
verify_ssl_cert=verify_ssl,
cert_file=cert_file,
key_file=key_file,
ca_cert=ca_cert_file,
username=username,
password=password,
timeout=timeout)
self.cursor = self.connection.cursor()
self.output_writer = output_writer or OutputWriter(
PrintWrapper(), is_tty)
self.last_connected_servers = crate_hosts

self.exit_code = 0
self.expanded_mode = False
self.sys_info_cmd = SysInfoCommand(self)
Expand All @@ -240,15 +248,18 @@ def __init__(self,
}
self.commands.update(built_in_commands)
self.logger = ColorPrinter(is_tty)

self.output_writer = output_writer or OutputWriter(PrintWrapper(), is_tty)
self.error_trace = error_trace
self._autocomplete = autocomplete
self._autocapitalize = autocapitalize
self.username = username
self.password = password
self.verify_ssl = verify_ssl
self.cert_file = cert_file
self.key_file = key_file
self.ca_cert_file = ca_cert_file
self.last_connected_servers = None
self.username = username
self.password = password


def get_num_columns(self):
return 80
Expand Down Expand Up @@ -527,15 +538,15 @@ def main():
# password authentication.
cmd = None
try:
cmd = _create_cmd(crate_hosts, error_trace, output_writer, is_tty,
args, password=password)
cmd = _create_shell(crate_hosts, error_trace, output_writer, is_tty,
args, password=password)
except (ProgrammingError, LocationParseError) as e:
if '401' in e.message and not force_passwd_prompt:
if is_tty:
password = getpass()
try:
cmd = _create_cmd(crate_hosts, error_trace, output_writer,
is_tty, args, password=password)
cmd = _create_shell(crate_hosts, error_trace, output_writer,
is_tty, args, password=password)
except (ProgrammingError, LocationParseError) as ex:
printer.warn(str(ex))
sys.exit(1)
Expand Down Expand Up @@ -567,27 +578,21 @@ def main():
conf.save()
sys.exit(cmd.exit())

def _create_cmd(crate_hosts, error_trace, output_writer, is_tty, args, timeout=None, password=None):
conn = connect(crate_hosts,
verify_ssl_cert=args.verify_ssl,
cert_file=args.cert_file,
key_file=args.key_file,
ca_cert=args.ca_cert_file,
username=args.username,
timeout=timeout,
password=password)
return CrateCmd(connection=conn,
error_trace=error_trace,
output_writer=output_writer,
is_tty=is_tty,
autocomplete=args.autocomplete,
autocapitalize=args.autocapitalize,
verify_ssl=args.verify_ssl,
cert_file=args.cert_file,
key_file=args.key_file,
ca_cert_file=args.ca_cert_file,
username=args.username,
password=password)
def _create_shell(crate_hosts, error_trace, output_writer, is_tty, args,
timeout=None, password=None):
return CrateShell(crate_hosts,
error_trace=error_trace,
output_writer=output_writer,
is_tty=is_tty,
autocomplete=args.autocomplete,
autocapitalize=args.autocapitalize,
verify_ssl=args.verify_ssl,
cert_file=args.cert_file,
key_file=args.key_file,
ca_cert_file=args.ca_cert_file,
username=args.username,
password=password,
timeout=timeout)

def file_with_permissions(path):
open(path, 'r').close()
Expand Down
88 changes: 44 additions & 44 deletions src/crate/crash/test_command.py
Expand Up @@ -12,8 +12,8 @@
from crate.client.exceptions import ProgrammingError
from urllib3.exceptions import LocationParseError

from .command import CrateCmd, main, get_stdin, noargs_command, Result, \
host_and_port, get_information_schema_query, stmt_type, _create_cmd, \
from .command import CrateShell, main, get_stdin, noargs_command, Result, \
host_and_port, get_information_schema_query, stmt_type, _create_shell, \
get_parser, parse_args
from .outputs import _val_len as val_len, OutputWriter
from .printer import ColorPrinter
Expand Down Expand Up @@ -203,7 +203,7 @@ def test_pprint_duplicate_keys(self):
"| name | name |",
"+------+------+",
"+------+------+\n"])
command = CrateCmd()
command = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
command.pprint([], ['name', 'name'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -215,7 +215,7 @@ def test_pprint_dont_guess_type(self):
"+---------+",
"| 0.50 |",
"+---------+\n"])
command = CrateCmd()
command = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
command.pprint([["0.50"]], ['version'])
self.assertEqual(expected, output.getvalue())
Expand Down Expand Up @@ -364,7 +364,7 @@ def test_tabulate_null_int_column(self):
'| 1 |',
'| NULL |',
'+------+\n'])
cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['x'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -380,7 +380,7 @@ def test_tabulate_boolean_int_column(self):
'| FALSE |',
'| 1 |',
'+-------+\n'])
cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['x'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -397,7 +397,7 @@ def test_multiline_header(self):
'| FALSE |',
'| 1 |',
'+-------+\n'])
cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['x\ny'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -415,7 +415,7 @@ def test_multiline_row(self):
'| name string | | |',
'| ) | | |',
'+-----------------------+-----+---+\n'])
cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['show create table foo', 'a', 'b'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -433,7 +433,7 @@ def test_tabulate_empty_line(self):
'| | Planet |',
'+------------------------------------+-------------+\n'])

cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['min(name)', 'kind'])
#assert 0
Expand All @@ -452,7 +452,7 @@ def test_empty_line_first_row_first_column(self):
'| Galactic Sector QQ7 Active J Gamma | Galaxy |',
'+------------------------------------+-------------+\n'])

cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['min(name)', 'kind'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -471,7 +471,7 @@ def test_empty_first_row(self):
'| Alpha Centauri | Alpha - Centauri |',
'+---------------------+-----------------------+\n'])

cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['name', 'replaced'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -489,7 +489,7 @@ def test_any_empty(self):
'| Features and conformance views | FALSE | 3 | SQL_LANGUAGES view |',
'+--------------------------------+--------------+----------------+--------------------+\n'])

cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['feature_name', 'is_supported', 'sub_feature_id', 'sub_feature_name'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -514,7 +514,7 @@ def test_first_column_first_row_empty(self):
'| NULL | 1.0 |',
'+------------------------------------+--------+\n'])

cmd = CrateCmd()
cmd = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
cmd.pprint(rows, cols=['name', '_score'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -531,7 +531,7 @@ def test_error_exit_code(self):
self.assertEqual(e.code, 1)

def test_verbose_with_error_trace(self):
command = CrateCmd(error_trace=True)
command = CrateShell(error_trace=True)
command.logger = Mock()
command.cursor.execute = Mock(side_effect=ProgrammingError(msg="the error message",
error_trace="error trace"))
Expand All @@ -540,7 +540,7 @@ def test_verbose_with_error_trace(self):
command.logger.critical.assert_called_with("\nerror trace")

def test_verbose_no_error_trace(self):
command = CrateCmd(error_trace=True)
command = CrateShell(error_trace=True)
command.logger = Mock()
command.cursor.execute = Mock(side_effect=ProgrammingError(msg="the error message",
error_trace=None))
Expand All @@ -556,7 +556,7 @@ def test_rendering_object(self):
'+-------------------------------+',
'| {"age": 42, "name": "Arthur"} |',
'+-------------------------------+\n'])
command = CrateCmd()
command = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
command.pprint([[user]], ['user'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -569,7 +569,7 @@ def test_rendering_array(self):
'+--------------------+',
'| ["Arthur", "Ford"] |',
'+--------------------+\n'])
command = CrateCmd()
command = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
command.pprint([[names]], ['names'])
self.assertEqual(expected, output.getvalue())
Expand All @@ -582,14 +582,14 @@ def test_rendering_float(self):
'| 3.1415926535 |',
'| 42.0 |',
'+---------------+\n'])
command = CrateCmd()
command = CrateShell()
with patch('sys.stdout', new_callable=StringIO) as output:
command.pprint([[3.1415926535], [42.0]], ['number'])
self.assertEqual(expected, output.getvalue())

def test_help_command(self):
"""Test output of help command"""
command = CrateCmd(is_tty=False)
command = CrateShell(is_tty=False)
expected = "\n".join([
'\\? print this help',
'\\autocapitalize toggle automatic capitalization of SQL keywords',
Expand All @@ -608,7 +608,7 @@ def test_help_command(self):
help_ = command.commands['?']
self.assertTrue(isinstance(help_, Command))
self.assertEqual(expected, help_(command))
command = CrateCmd(is_tty=False)
command = CrateShell(is_tty=False)

output = StringIO()
command.logger = ColorPrinter(False, stream=output)
Expand Down Expand Up @@ -648,16 +648,16 @@ def test_wrong_host_format(self):
crate_hosts = [host_and_port(h) for h in args.hosts]

with self.assertRaises(LocationParseError):
_create_cmd(crate_hosts, False, None, False, args)
_create_shell(crate_hosts, False, None, False, args)

def test_command_timeout(self):
sys.argv = ["testcrash", "--hosts", self.crate_host]
parser = get_parser()
args = parse_args(parser)

crate_hosts = [host_and_port(h) for h in args.hosts]
crateCmd = _create_cmd(crate_hosts, False, None, False, args, None)
crateCmd.execute("""
crash = _create_shell(crate_hosts, False, None, False, args, None)
crash.execute("""
CREATE FUNCTION fib(long)
RETURNS LONG
LANGUAGE javascript AS '
Expand All @@ -671,17 +671,17 @@ def test_command_timeout(self):
slow_query = "SELECT fib(35)"

# without verbose
crateCmd = _create_cmd(crate_hosts, False, None, False, args, timeout)
crateCmd.logger = Mock()
crateCmd.execute(slow_query)
crateCmd.logger.warn.assert_any_call("Use \connect <server> to connect to one or more servers first.")
crash = _create_shell(crate_hosts, False, None, False, args, timeout)
crash.logger = Mock()
crash.execute(slow_query)
crash.logger.warn.assert_any_call("Use \connect <server> to connect to one or more servers first.")

# with verbose
crateCmd = _create_cmd(crate_hosts, True, None, False, args, timeout)
crateCmd.logger = Mock()
crateCmd.execute(slow_query)
crateCmd.logger.warn.assert_any_call("No more Servers available, exception from last server: HTTPConnectionPool(host='127.0.0.1', port=44209): Read timed out. (read timeout=0.01)")
crateCmd.logger.warn.assert_any_call("Use \connect <server> to connect to one or more servers first.")
crash = _create_shell(crate_hosts, True, None, False, args, timeout)
crash.logger = Mock()
crash.execute(slow_query)
crash.logger.warn.assert_any_call("No more Servers available, exception from last server: HTTPConnectionPool(host='127.0.0.1', port=44209): Read timed out. (read timeout=0.01)")
crash.logger.warn.assert_any_call("Use \connect <server> to connect to one or more servers first.")

def test_username_param(self):
sys.argv = ["testcrash",
Expand All @@ -691,10 +691,10 @@ def test_username_param(self):
parser = get_parser()
args = parse_args(parser)
crate_hosts = [host_and_port(h) for h in args.hosts]
crateCmd = _create_cmd(crate_hosts, False, None, False, args)
crash = _create_shell(crate_hosts, False, None, False, args)

self.assertEqual(crateCmd.username, "crate")
self.assertEqual(crateCmd.connection.client.username, "crate")
self.assertEqual(crash.username, "crate")
self.assertEqual(crash.connection.client.username, "crate")

def test_ssl_params(self):
tmpdirname = tempfile.mkdtemp()
Expand All @@ -717,19 +717,19 @@ def test_ssl_params(self):
args = parse_args(parser)

crate_hosts = [host_and_port(h) for h in args.hosts]
crateCmd = _create_cmd(crate_hosts, False, None, False, args)
crash = _create_shell(crate_hosts, False, None, False, args)

self.assertEqual(crateCmd.verify_ssl, False)
self.assertEqual(crateCmd.connection.client._pool_kw['cert_reqs'], ssl.CERT_NONE)
self.assertEqual(crash.verify_ssl, False)
self.assertEqual(crash.connection.client._pool_kw['cert_reqs'], ssl.CERT_NONE)

self.assertEqual(crateCmd.cert_file, cert_filename)
self.assertEqual(crateCmd.connection.client._pool_kw['cert_file'], cert_filename)
self.assertEqual(crash.cert_file, cert_filename)
self.assertEqual(crash.connection.client._pool_kw['cert_file'], cert_filename)

self.assertEqual(crateCmd.key_file, key_filename)
self.assertEqual(crateCmd.connection.client._pool_kw['key_file'], key_filename)
self.assertEqual(crash.key_file, key_filename)
self.assertEqual(crash.connection.client._pool_kw['key_file'], key_filename)

self.assertEqual(crateCmd.ca_cert_file, ca_cert_filename)
self.assertEqual(crateCmd.connection.client._pool_kw['ca_certs'], ca_cert_filename)
self.assertEqual(crash.ca_cert_file, ca_cert_filename)
self.assertEqual(crash.connection.client._pool_kw['ca_certs'], ca_cert_filename)


def test_ssl_params_missing_file(self):
Expand Down