summaryrefslogtreecommitdiffstats
path: root/test/test_main.py
blob: 00fdc1bdeb938457f83a0e85a4c99fce87af8840 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
import os

import click
from click.testing import CliRunner

from mycli.main import MyCli, cli, thanks_picker
from mycli.packages.special.main import COMMANDS as SPECIAL_COMMANDS
from mycli.sqlexecute import ServerInfo
from .utils import USER, HOST, PORT, PASSWORD, dbtest, run

from textwrap import dedent
from collections import namedtuple

from tempfile import NamedTemporaryFile
from textwrap import dedent


test_dir = os.path.abspath(os.path.dirname(__file__))
project_dir = os.path.dirname(test_dir)
default_config_file = os.path.join(project_dir, 'test', 'myclirc')
login_path_file = os.path.join(test_dir, 'mylogin.cnf')

os.environ['MYSQL_TEST_LOGIN_FILE'] = login_path_file
CLI_ARGS = ['--user', USER, '--host', HOST, '--port', PORT,
            '--password', PASSWORD, '--myclirc', default_config_file,
            '--defaults-file', default_config_file,
            '_test_db']


@dbtest
def test_execute_arg(executor):
    run(executor, 'create table test (a text)')
    run(executor, 'insert into test values("abc")')

    sql = 'select * from test;'
    runner = CliRunner()
    result = runner.invoke(cli, args=CLI_ARGS + ['-e', sql])

    assert result.exit_code == 0
    assert 'abc' in result.output

    result = runner.invoke(cli, args=CLI_ARGS + ['--execute', sql])

    assert result.exit_code == 0
    assert 'abc' in result.output

    expected = 'a\nabc\n'

    assert expected in result.output


@dbtest
def test_execute_arg_with_table(executor):
    run(executor, 'create table test (a text)')
    run(executor, 'insert into test values("abc")')

    sql = 'select * from test;'
    runner = CliRunner()
    result = runner.invoke(cli, args=CLI_ARGS + ['-e', sql] + ['--table'])
    expected = '+-----+\n| a   |\n+-----+\n| abc |\n+-----+\n'

    assert result.exit_code == 0
    assert expected in result.output


@dbtest
def test_execute_arg_with_csv(executor):
    run(executor, 'create table test (a text)')
    run(executor, 'insert into test values("abc")')

    sql = 'select * from test;'
    runner = CliRunner()
    result = runner.invoke(cli, args=CLI_ARGS + ['-e', sql] + ['--csv'])
    expected = '"a"\n"abc"\n'

    assert result.exit_code == 0
    assert expected in "".join(result.output)


@dbtest
def test_batch_mode(executor):
    run(executor, '''create table test(a text)''')
    run(executor, '''insert into test values('abc'), ('def'), ('ghi')''')

    sql = (
        'select count(*) from test;\n'
        'select * from test limit 1;'
    )

    runner = CliRunner()
    result = runner.invoke(cli, args=CLI_ARGS, input=sql)

    assert result.exit_code == 0
    assert 'count(*)\n3\na\nabc\n' in "".join(result.output)


@dbtest
def test_batch_mode_table(executor):
    run(executor, '''create table test(a text)''')
    run(executor, '''insert into test values('abc'), ('def'), ('ghi')''')

    sql = (
        'select count(*) from test;\n'
        'select * from test limit 1;'
    )

    runner = CliRunner()
    result = runner.invoke(cli, args=CLI_ARGS + ['-t'], input=sql)

    expected = (dedent("""\
        +----------+
        | count(*) |
        +----------+
        | 3        |
        +----------+
        +-----+
        | a   |
        +-----+
        | abc |
        +-----+"""))

    assert result.exit_code == 0
    assert expected in result.output


@dbtest
def test_batch_mode_csv(executor):
    run(executor, '''create table test(a text, b text)''')
    run(executor,
        '''insert into test (a, b) values('abc', 'de\nf'), ('ghi', 'jkl')''')

    sql = 'select * from test;'

    runner = CliRunner()
    result = runner.invoke(cli, args=CLI_ARGS + ['--csv'], input=sql)

    expected = '"a","b"\n"abc","de\nf"\n"ghi","jkl"\n'

    assert result.exit_code == 0
    assert expected in "".join(result.output)


def test_thanks_picker_utf8():
    name = thanks_picker()
    assert name and isinstance(name, str)


def test_help_strings_end_with_periods():
    """Make sure click options have help text that end with a period."""
    for param in cli.params:
        if isinstance(param, click.core.Option):
            assert hasattr(param, 'help')
            assert param.help.endswith('.')


def test_command_descriptions_end_with_periods():
    """Make sure that mycli commands' descriptions end with a period."""
    MyCli()
    for _, command in SPECIAL_COMMANDS.items():
        assert command[3].endswith('.')


def output(monkeypatch, terminal_size, testdata, explicit_pager, expect_pager):
    global clickoutput
    clickoutput = ""
    m = MyCli(myclirc=default_config_file)

    class TestOutput():
        def get_size(self):
            size = namedtuple('Size', 'rows columns')
            size.columns, size.rows = terminal_size
            return size

    class TestExecute():
        host = 'test'
        user = 'test'
        dbname = 'test'
        server_info = ServerInfo.from_version_string('unknown')
        port = 0

        def server_type(self):
            return ['test']

    class PromptBuffer():
        output = TestOutput()

    m.prompt_app = PromptBuffer()
    m.sqlexecute = TestExecute()
    m.explicit_pager = explicit_pager

    def echo_via_pager(s):
        assert expect_pager
        global clickoutput
        clickoutput += "".join(s)

    def secho(s):
        assert not expect_pager
        global clickoutput
        clickoutput += s + "\n"

    monkeypatch.setattr(click, 'echo_via_pager', echo_via_pager)
    monkeypatch.setattr(click, 'secho', secho)
    m.output(testdata)
    if clickoutput.endswith("\n"):
        clickoutput = clickoutput[:-1]
    assert clickoutput == "\n".join(testdata)


def test_conditional_pager(monkeypatch):
    testdata = "Lorem ipsum dolor sit amet consectetur adipiscing elit sed do".split(
        " ")
    # User didn't set pager, output doesn't fit screen -> pager
    output(
        monkeypatch,
        terminal_size=(5, 10),
        testdata=testdata,
        explicit_pager=False,
        expect_pager=True
    )
    # User didn't set pager, output fits screen -> no pager
    output(
        monkeypatch,
        terminal_size=(20, 20),
        testdata=testdata,
        explicit_pager=False,
        expect_pager=False
    )
    # User manually configured pager, output doesn't fit screen -> pager
    output(
        monkeypatch,
        terminal_size=(5, 10),
        testdata=testdata,
        explicit_pager=True,
        expect_pager=True
    )
    # User manually configured pager, output fit screen -> pager
    output(
        monkeypatch,
        terminal_size=(20, 20),
        testdata=testdata,
        explicit_pager=True,
        expect_pager=True
    )

    SPECIAL_COMMANDS['nopager'].handler()
    output(
        monkeypatch,
        terminal_size=(5, 10),
        testdata=testdata,
        explicit_pager=False,
        expect_pager=False
    )
    SPECIAL_COMMANDS['pager'].handler('')


def test_reserved_space_is_integer():
    """Make sure that reserved space is returned as an integer."""
    def stub_terminal_size():
        return (5, 5)

    old_func = click.get_terminal_size

    click.get_terminal_size = stub_terminal_size
    mycli = MyCli()
    assert isinstance(mycli.get_reserved_space(), int)

    click.get_terminal_size = old_func


def test_list_dsn():
    runner = CliRunner()
    with NamedTemporaryFile(mode="w") as myclirc:
        myclirc.write(dedent("""\
            [alias_dsn]
            test = mysql://test/test
            """))
        myclirc.flush()
        args = ['--list-dsn', '--myclirc', myclirc.name]
        result = runner.invoke(cli, args=args)
        assert result.output == "test\n"
        result = runner.invoke(cli, args=args + ['--verbose'])
        assert result.output == "test : mysql://test/test\n"


def test_list_ssh_config():
    runner = CliRunner()
    with NamedTemporaryFile(mode="w") as ssh_config:
        ssh_config.write(dedent("""\
            Host test
                Hostname test.example.com
                User joe
                Port 22222
                IdentityFile ~/.ssh/gateway
        """))
        ssh_config.flush()
        args = ['--list-ssh-config', '--ssh-config-path', ssh_config.name]
        result = runner.invoke(cli, args=args)
        assert "test\n" in result.output
        result = runner.invoke(cli, args=args + ['--verbose'])
        assert "test : test.example.com\n" in result.output


def test_dsn(monkeypatch):
    # Setup classes to mock mycli.main.MyCli
    class Formatter:
        format_name = None
    class Logger:
        def debug(self, *args, **args_dict):
            pass
        def warning(self, *args, **args_dict):
            pass
    class MockMyCli:
        config = {'alias_dsn': {}}
        def __init__(self, **args):
            self.logger = Logger()
            self.destructive_warning = False
            self.formatter = Formatter()
        def connect(self, **args):
            MockMyCli.connect_args = args
        def run_query(self, query, new_line=True):
            pass

    import mycli.main
    monkeypatch.setattr(mycli.main, 'MyCli', MockMyCli)
    runner = CliRunner()

    # When a user supplies a DSN as database argument to mycli,
    # use these values.
    result = runner.invoke(mycli.main.cli, args=[
        "mysql://dsn_user:dsn_passwd@dsn_host:1/dsn_database"]
    )
    assert result.exit_code == 0, result.output + " " + str(result.exception)
    assert \
        MockMyCli.connect_args["user"] == "dsn_user" and \
        MockMyCli.connect_args["passwd"] == "dsn_passwd" and \
        MockMyCli.connect_args["host"] == "dsn_host" and \
        MockMyCli.connect_args["port"] == 1 and \
        MockMyCli.connect_args["database"] == "dsn_database"

    MockMyCli.connect_args = None

    # When a use supplies a DSN as database argument to mycli,
    # and used command line arguments, use the command line
    # arguments.
    result = runner.invoke(mycli.main.cli, args=[
        "mysql://dsn_user:dsn_passwd@dsn_host:2/dsn_database",
        "--user", "arg_user",
        "--password", "arg_password",
        "--host", "arg_host",
        "--port", "3",
        "--database", "arg_database",
    ])
    assert result.exit_code == 0, result.output + " " + str(result.exception)
    assert \
        MockMyCli.connect_args["user"] == "arg_user" and \
        MockMyCli.connect_args["passwd"] == "arg_password" and \
        MockMyCli.connect_args["host"] == "arg_host" and \
        MockMyCli.connect_args["port"] == 3 and \
        MockMyCli.connect_args["database"] == "arg_database"

    MockMyCli.config = {
        'alias_dsn': {
            'test': 'mysql://alias_dsn_user:alias_dsn_passwd@alias_dsn_host:4/alias_dsn_database'
        }
    }
    MockMyCli.connect_args = None

    # When a user uses a DSN from the configuration file (alias_dsn),
    # use these values.
    result = runner.invoke(cli, args=['--dsn', 'test'])
    assert result.exit_code == 0, result.output + " " + str(result.exception)
    assert \
        MockMyCli.connect_args["user"] == "alias_dsn_user" and \
        MockMyCli.connect_args["passwd"] == "alias_dsn_passwd" and \
        MockMyCli.connect_args["host"] == "alias_dsn_host" and \
        MockMyCli.connect_args["port"] == 4 and \
        MockMyCli.connect_args["database"] == "alias_dsn_database"

    MockMyCli.config = {
        'alias_dsn': {
            'test': 'mysql://alias_dsn_user:alias_dsn_passwd@alias_dsn_host:4/alias_dsn_database'
        }
    }
    MockMyCli.connect_args = None

    # When a user uses a DSN from the configuration file (alias_dsn)
    # and used command line arguments, use the command line arguments.
    result = runner.invoke(cli, args=[
        '--dsn', 'test', '',
        "--user", "arg_user",
        "--password", "arg_password",
        "--host", "arg_host",
        "--port", "5",
        "--database", "arg_database",
    ])
    assert result.exit_code == 0, result.output + " " + str(result.exception)
    assert \
        MockMyCli.connect_args["user"] == "arg_user" and \
        MockMyCli.connect_args["passwd"] == "arg_password" and \
        MockMyCli.connect_args["host"] == "arg_host" and \
        MockMyCli.connect_args["port"] == 5 and \
        MockMyCli.connect_args["database"] == "arg_database"

    # Use a DSN without password
    result = runner.invoke(mycli.main.cli, args=[
        "mysql://dsn_user@dsn_host:6/dsn_database"]
    )
    assert result.exit_code == 0, result.output + " " + str(result.exception)
    assert \
        MockMyCli.connect_args["user"] == "dsn_user" and \
        MockMyCli.connect_args["passwd"] is None and \
        MockMyCli.connect_args["host"] == "dsn_host" and \
        MockMyCli.connect_args["port"] == 6 and \
        MockMyCli.connect_args["database"] == "dsn_database"


def test_ssh_config(monkeypatch):
    # Setup classes to mock mycli.main.MyCli
    class Formatter:
        format_name = None

    class Logger:
        def debug(self, *args, **args_dict):
            pass

        def warning(self, *args, **args_dict):
            pass

    class MockMyCli:
        config = {'alias_dsn': {}}

        def __init__(self, **args):
            self.logger = Logger()
            self.destructive_warning = False
            self.formatter = Formatter()

        def connect(self, **args):
            MockMyCli.connect_args = args

        def run_query(self, query, new_line=True):
            pass

    import mycli.main
    monkeypatch.setattr(mycli.main, 'MyCli', MockMyCli)
    runner = CliRunner()

    # Setup temporary configuration
    with NamedTemporaryFile(mode="w") as ssh_config:
        ssh_config.write(dedent("""\
            Host test
                Hostname test.example.com
                User joe
                Port 22222
                IdentityFile ~/.ssh/gateway
        """))
        ssh_config.flush()

        # When a user supplies a ssh config.
        result = runner.invoke(mycli.main.cli, args=[
            "--ssh-config-path",
            ssh_config.name,
            "--ssh-config-host",
            "test"
        ])
        assert result.exit_code == 0, result.output + \
            " " + str(result.exception)
        assert \
            MockMyCli.connect_args["ssh_user"] == "joe" and \
            MockMyCli.connect_args["ssh_host"] == "test.example.com" and \
            MockMyCli.connect_args["ssh_port"] == 22222 and \
            MockMyCli.connect_args["ssh_key_filename"] == os.getenv(
                "HOME") + "/.ssh/gateway"

        # When a user supplies a ssh config host as argument to mycli,
        # and used command line arguments, use the command line
        # arguments.
        result = runner.invoke(mycli.main.cli, args=[
            "--ssh-config-path",
            ssh_config.name,
            "--ssh-config-host",
            "test",
            "--ssh-user", "arg_user",
            "--ssh-host", "arg_host",
            "--ssh-port", "3",
            "--ssh-key-filename", "/path/to/key"
        ])
        assert result.exit_code == 0, result.output + \
            " " + str(result.exception)
        assert \
            MockMyCli.connect_args["ssh_user"] == "arg_user" and \
            MockMyCli.connect_args["ssh_host"] == "arg_host" and \
            MockMyCli.connect_args["ssh_port"] == 3 and \
            MockMyCli.connect_args["ssh_key_filename"] == "/path/to/key"


@dbtest
def test_init_command_arg(executor):
    init_command = "set sql_select_limit=1000"
    sql = 'show variables like "sql_select_limit";'
    runner = CliRunner()
    result = runner.invoke(
        cli, args=CLI_ARGS + ["--init-command", init_command], input=sql
    )

    expected = "sql_select_limit\t1000\n"
    assert result.exit_code == 0
    assert expected in result.output


@dbtest
def test_init_command_multiple_arg(executor):
    init_command = 'set sql_select_limit=2000; set max_join_size=20000'
    sql = (
        'show variables like "sql_select_limit";\n'
        'show variables like "max_join_size"'
    )
    runner = CliRunner()
    result = runner.invoke(
        cli, args=CLI_ARGS + ['--init-command', init_command], input=sql
    )

    expected_sql_select_limit = 'sql_select_limit\t2000\n'
    expected_max_join_size = 'max_join_size\t20000\n'

    assert result.exit_code == 0
    assert expected_sql_select_limit in result.output
    assert expected_max_join_size in result.output