-
Notifications
You must be signed in to change notification settings - Fork 689
Expand file tree
/
Copy pathtest_main.py
More file actions
2411 lines (1986 loc) · 74.9 KB
/
test_main.py
File metadata and controls
2411 lines (1986 loc) · 74.9 KB
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# type: ignore
from collections import namedtuple
from contextlib import redirect_stderr, redirect_stdout
import csv
import io
import os
import shutil
from tempfile import NamedTemporaryFile
from textwrap import dedent
from types import SimpleNamespace
from typing import Any, cast
import click
from click.testing import CliRunner
import pymysql
from pymysql.err import OperationalError
import pytest
from mycli import main
from mycli.constants import (
DEFAULT_DATABASE,
DEFAULT_HOST,
DEFAULT_PORT,
DEFAULT_USER,
TEST_DATABASE,
)
from mycli.main import EMPTY_PASSWORD_FLAG_SENTINEL, MyCli, click_entrypoint
import mycli.main_modes.repl as repl_mode
import mycli.packages.special
from mycli.packages.special.main import COMMANDS as SPECIAL_COMMANDS
from mycli.packages.sqlresult import SQLResult
from mycli.sqlexecute import ServerInfo, SQLExecute
from test.utils import (
DATABASE,
HOST,
PASSWORD,
PORT,
TEMPFILE_PREFIX,
USER,
DummyFormatter,
DummyLogger,
FakeCursorBase,
RecordingSQLExecute,
ReusableLock,
call_click_entrypoint_direct,
dbtest,
make_bare_mycli,
make_dummy_mycli_class,
run,
)
pytests_dir = os.path.abspath(os.path.dirname(__file__))
project_root_dir = os.path.abspath(os.path.join(pytests_dir, '..', '..'))
default_config_file = os.path.join(project_root_dir, 'test', 'myclirc')
login_path_file = os.path.join(project_root_dir, 'test', 'mylogin.cnf')
os.environ["MYSQL_TEST_LOGIN_FILE"] = login_path_file
CLI_ARGS_WITHOUT_DB = [
"--user",
USER,
"--host",
HOST,
"--port",
PORT,
"--password",
PASSWORD,
"--myclirc",
default_config_file,
"--defaults-file",
default_config_file,
]
CLI_ARGS = CLI_ARGS_WITHOUT_DB + [TEST_DATABASE]
@dbtest
def test_binary_display_hex(executor):
m = MyCli()
m.sqlexecute = SQLExecute(
None,
USER,
PASSWORD,
HOST,
PORT,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
m.explicit_pager = False
sqlresult = next(m.sqlexecute.run("select b'01101010' AS binary_test"))
formatted = m.format_sqlresult(
sqlresult,
is_expanded=False,
is_redirected=False,
null_string="<null>",
numeric_alignment="right",
binary_display="hex",
max_width=None,
)
f = io.StringIO()
with redirect_stdout(f):
m.output(formatted, sqlresult)
expected = " 0x6a "
output = f.getvalue()
assert expected in output
@dbtest
def test_binary_display_utf8(executor):
m = MyCli()
m.sqlexecute = SQLExecute(
None,
USER,
PASSWORD,
HOST,
PORT,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
m.explicit_pager = False
sqlresult = next(m.sqlexecute.run("select b'01101010' AS binary_test"))
formatted = m.format_sqlresult(
sqlresult,
is_expanded=False,
is_redirected=False,
null_string="<null>",
numeric_alignment="right",
binary_display="utf8",
max_width=None,
)
f = io.StringIO()
with redirect_stdout(f):
m.output(formatted, sqlresult)
expected = " j "
output = f.getvalue()
assert expected in output
@dbtest
def test_select_from_empty_table(executor):
run(executor, """create table t1(id int)""")
sql = "select * from t1"
runner = CliRunner()
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["-t"], input=sql)
expected = dedent("""\
+----+
| id |
+----+
+----+""")
assert expected in result.output
def test_filtered_sys_argv_maps_single_dash_h_to_help(monkeypatch):
import mycli.main
monkeypatch.setattr(mycli.main.sys, 'argv', ['mycli', '-h'])
assert mycli.main.filtered_sys_argv() == ['--help']
def test_filtered_sys_argv_preserves_host_option_usage(monkeypatch):
import mycli.main
monkeypatch.setattr(mycli.main.sys, 'argv', ['mycli', '-h', 'example.com'])
assert mycli.main.filtered_sys_argv() == ['-h', 'example.com']
def test_main_dash_h_and_help_have_equivalent_output(monkeypatch):
import mycli.main
def run_main(argv):
stdout = io.StringIO()
stderr = io.StringIO()
monkeypatch.setattr(mycli.main.sys, 'argv', argv)
with redirect_stdout(stdout), redirect_stderr(stderr):
result = mycli.main.main()
return result, stdout.getvalue(), stderr.getvalue()
dash_h_result, dash_h_stdout, dash_h_stderr = run_main(['mycli', '-h'])
dash_help_result, dash_help_stdout, dash_help_stderr = run_main(['mycli', '--help'])
assert dash_h_result == 0
assert dash_help_result == 0
assert dash_h_stdout == dash_help_stdout
assert dash_h_stderr == dash_help_stderr
@dbtest
def test_ssl_mode_on(executor, capsys):
runner = CliRunner()
ssl_mode = "on"
sql = "select * from performance_schema.session_status where variable_name = 'Ssl_cipher'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--csv", "--ssl-mode", ssl_mode], input=sql)
result_dict = next(csv.DictReader(result.stdout.split("\n")))
ssl_cipher = result_dict.get("VARIABLE_VALUE", None)
assert ssl_cipher
@dbtest
def test_ssl_mode_auto(executor, capsys):
runner = CliRunner()
ssl_mode = "auto"
sql = "select * from performance_schema.session_status where variable_name = 'Ssl_cipher'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--csv", "--ssl-mode", ssl_mode], input=sql)
result_dict = next(csv.DictReader(result.stdout.split("\n")))
ssl_cipher = result_dict.get("VARIABLE_VALUE", None)
assert ssl_cipher
@dbtest
def test_ssl_mode_off(executor, capsys):
runner = CliRunner()
ssl_mode = "off"
sql = "select * from performance_schema.session_status where variable_name = 'Ssl_cipher'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--csv", "--ssl-mode", ssl_mode], input=sql)
result_dict = next(csv.DictReader(result.stdout.split("\n")))
ssl_cipher = result_dict.get("VARIABLE_VALUE", None)
assert not ssl_cipher
@dbtest
def test_ssl_mode_overrides_ssl(executor, capsys):
runner = CliRunner()
ssl_mode = "off"
sql = "select * from performance_schema.session_status where variable_name = 'Ssl_cipher'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--csv", "--ssl-mode", ssl_mode, "--ssl"], input=sql)
result_dict = next(csv.DictReader(result.stdout.split("\n")))
ssl_cipher = result_dict.get("VARIABLE_VALUE", None)
assert not ssl_cipher
@dbtest
def test_ssl_mode_overrides_no_ssl(executor, capsys):
runner = CliRunner()
ssl_mode = "on"
sql = "select * from performance_schema.session_status where variable_name = 'Ssl_cipher'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--csv", "--ssl-mode", ssl_mode, "--no-ssl"], input=sql)
result_dict = next(csv.DictReader(result.stdout.split("\n")))
ssl_cipher = result_dict.get("VARIABLE_VALUE", None)
assert ssl_cipher
@dbtest
def test_reconnect_database_is_selected(executor, capsys):
m = MyCli()
m.register_special_commands()
m.sqlexecute = SQLExecute(
None,
USER,
PASSWORD,
HOST,
PORT,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
try:
next(m.sqlexecute.run(f"use {DATABASE}"))
next(m.sqlexecute.run(f"kill {m.sqlexecute.connection_id}"))
except OperationalError:
pass # expected as the connection was killed
except Exception as e:
raise e
m.reconnect()
try:
next(m.sqlexecute.run("show tables")).rows.fetchall()
except Exception as e:
raise e
@dbtest
def test_reconnect_no_database(executor, capsys):
m = MyCli()
m.register_special_commands()
m.sqlexecute = SQLExecute(
None,
USER,
PASSWORD,
HOST,
PORT,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
sql = "\\r"
result = next(mycli.packages.special.execute(executor, sql))
stdout, _stderr = capsys.readouterr()
assert result.status is None
assert "Already connected" in stdout
@dbtest
def test_reconnect_with_different_database(executor):
m = MyCli()
m.register_special_commands()
m.sqlexecute = SQLExecute(
None,
USER,
PASSWORD,
HOST,
PORT,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
database_1 = TEST_DATABASE
database_2 = DEFAULT_DATABASE
sql_1 = f"use {database_1}"
sql_2 = f"\\r {database_2}"
_result_1 = next(mycli.packages.special.execute(executor, sql_1))
result_2 = next(mycli.packages.special.execute(executor, sql_2))
expected = f'You are now connected to database "{database_2}" as user "{USER}"'
assert expected in result_2.status
@dbtest
def test_reconnect_with_same_database(executor):
m = MyCli()
m.register_special_commands()
m.sqlexecute = SQLExecute(
None,
USER,
PASSWORD,
HOST,
PORT,
None,
None,
None,
None,
None,
None,
None,
None,
None,
None,
)
database = DEFAULT_DATABASE
sql = f"\\u {database}"
result = next(mycli.packages.special.execute(executor, sql))
sql = f"\\r {database}"
result = next(mycli.packages.special.execute(executor, sql))
expected = f'You are already connected to database "{database}" as user "{USER}"'
assert expected in result.status
@dbtest
def test_prompt_no_host_only_socket(executor):
mycli = MyCli()
mycli.prompt_format = "\\t \\u@\\h:\\d> "
mycli.sqlexecute = SQLExecute
mycli.sqlexecute.server_info = ServerInfo.from_version_string("8.0.44-0ubuntu0.24.04.1")
mycli.sqlexecute.host = None
mycli.sqlexecute.socket = "/var/run/mysqld/mysqld.sock"
mycli.sqlexecute.user = DEFAULT_USER
mycli.sqlexecute.dbname = DEFAULT_DATABASE
mycli.sqlexecute.port = DEFAULT_PORT
prompt = repl_mode.get_prompt(mycli, mycli.prompt_format, 0)
assert prompt == f"MySQL {DEFAULT_USER}@{DEFAULT_HOST}:{DEFAULT_DATABASE}> "
@dbtest
def test_prompt_socket_overrides_port(executor):
mycli = MyCli()
mycli.prompt_format = "\\t \\u@\\h:\\k \\d> "
mycli.sqlexecute = SQLExecute
mycli.sqlexecute.server_info = ServerInfo.from_version_string("8.0.44-0ubuntu0.24.04.1")
mycli.sqlexecute.host = None
mycli.sqlexecute.socket = "/var/run/mysqld/mysqld.sock"
mycli.sqlexecute.user = DEFAULT_USER
mycli.sqlexecute.dbname = DEFAULT_DATABASE
mycli.sqlexecute.port = DEFAULT_PORT
prompt = repl_mode.get_prompt(mycli, mycli.prompt_format, 0)
assert prompt == f"MySQL {DEFAULT_USER}@{DEFAULT_HOST}:mysqld.sock {DEFAULT_DATABASE}> "
@dbtest
def test_prompt_socket_short_host(executor):
mycli = MyCli()
mycli.prompt_format = "\\t \\u@\\H:\\k \\d> "
mycli.sqlexecute = SQLExecute
mycli.sqlexecute.server_info = ServerInfo.from_version_string("8.0.44-0ubuntu0.24.04.1")
mycli.sqlexecute.host = f'{DEFAULT_HOST}.localdomain'
mycli.sqlexecute.socket = None
mycli.sqlexecute.user = DEFAULT_USER
mycli.sqlexecute.dbname = DEFAULT_DATABASE
mycli.sqlexecute.port = DEFAULT_PORT
prompt = repl_mode.get_prompt(mycli, mycli.prompt_format, 0)
assert prompt == f"MySQL {DEFAULT_USER}@{DEFAULT_HOST}:{DEFAULT_PORT} {DEFAULT_DATABASE}> "
@dbtest
def test_enable_show_warnings(executor):
mycli = MyCli()
mycli.register_special_commands()
sql = "\\W"
result = run(executor, sql)
assert result[0]["status"] == "Show warnings enabled."
@dbtest
def test_disable_show_warnings(executor):
mycli = MyCli()
mycli.register_special_commands()
sql = "\\w"
result = run(executor, sql)
assert result[0]["status"] == "Show warnings disabled."
@dbtest
def test_output_ddl_with_warning_and_show_warnings_enabled(executor):
runner = CliRunner()
db = TEST_DATABASE
table = "table_that_definitely_does_not_exist_1234"
sql = f"DROP TABLE IF EXISTS {db}.{table}"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--show-warnings", "--no-warn"], input=sql)
expected = f"Level\tCode\tMessage\nNote\t1051\tUnknown table '{db}.table_that_definitely_does_not_exist_1234'\n"
assert expected in result.output
@dbtest
def test_output_with_warning_and_show_warnings_enabled(executor):
runner = CliRunner()
sql = "SELECT 1 + '0 foo'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--show-warnings"], input=sql)
expected = "1 + '0 foo'\n1.0\nLevel\tCode\tMessage\nWarning\t1292\tTruncated incorrect DOUBLE value: '0 foo'\n"
assert expected in result.output
@dbtest
def test_output_with_warning_and_show_warnings_disabled(executor):
runner = CliRunner()
sql = "SELECT 1 + '0 foo'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--no-show-warnings"], input=sql)
expected = "1 + '0 foo'\n1.0\nLevel\tCode\tMessage\nWarning\t1292\tTruncated incorrect DOUBLE value: '0 foo'\n"
assert expected not in result.output
@dbtest
def test_no_show_warnings_overrides_myclirc_setting(executor, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
runner = CliRunner()
sql = 'EXPLAIN SELECT 1'
expected = 'select 1'
with NamedTemporaryFile(prefix=TEMPFILE_PREFIX, mode='w', delete=False) as myclirc:
myclirc.write(
dedent("""\
[main]
show_warnings = True
""")
)
myclirc.flush()
args = [
'--user',
USER,
'--host',
HOST,
'--port',
PORT,
'--password',
PASSWORD,
'--myclirc',
myclirc.name,
'--defaults-file',
default_config_file,
TEST_DATABASE,
]
result = runner.invoke(click_entrypoint, args=args, input=sql)
assert expected in result.output
result = runner.invoke(click_entrypoint, args=args + ['--no-show-warnings'], input=sql)
assert expected not in result.output
try:
if os.path.exists(myclirc.name):
os.remove(myclirc.name)
except Exception as e:
print(f"An error occurred while attempting to delete the file: {e}")
@dbtest
def test_output_with_multiple_warnings_in_single_statement(executor):
runner = CliRunner()
sql = "SELECT 1 + '0 foo', 2 + '0 foo'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--show-warnings"], input=sql)
expected = (
"1 + '0 foo'\t2 + '0 foo'\n"
"1.0\t2.0\n"
"Level\tCode\tMessage\n"
"Warning\t1292\tTruncated incorrect DOUBLE value: '0 foo'\n"
"Warning\t1292\tTruncated incorrect DOUBLE value: '0 foo'\n"
)
assert expected in result.output
@dbtest
def test_output_with_multiple_warnings_in_multiple_statements(executor):
runner = CliRunner()
sql = "SELECT 1 + '0 foo'; SELECT 2 + '0 foo'"
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--show-warnings"], input=sql)
expected = (
"1 + '0 foo'\n"
"1.0\n"
"Level\tCode\tMessage\n"
"Warning\t1292\tTruncated incorrect DOUBLE value: '0 foo'\n"
"2 + '0 foo'\n"
"2.0\n"
"Level\tCode\tMessage\n"
"Warning\t1292\tTruncated incorrect DOUBLE value: '0 foo'\n"
)
assert expected in result.output
@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(click_entrypoint, args=CLI_ARGS + ["-e", sql])
assert result.exit_code == 0
assert "abc" in result.output
result = runner.invoke(click_entrypoint, 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_checkpoint(executor):
run(executor, "create table test (a text)")
run(executor, 'insert into test values("abc")')
sql = "select * from test;"
runner = CliRunner()
with NamedTemporaryFile(prefix=TEMPFILE_PREFIX, mode="w", delete=False) as checkpoint:
checkpoint.close()
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--execute", sql, f"--checkpoint={checkpoint.name}"])
assert result.exit_code == 0
with open(checkpoint.name, 'r') as f:
contents = f.read()
assert sql in contents
os.remove(checkpoint.name)
sql = 'select 10 from nonexistent_table;'
result = runner.invoke(click_entrypoint, args=CLI_ARGS + ["--execute", sql, f"--checkpoint={checkpoint.name}"])
assert result.exit_code != 0
with open(checkpoint.name, 'r') as f:
contents = f.read()
assert sql not in contents
# delete=False means we should try to clean up
# we don't really need "try" here as open() would have already failed
try:
if os.path.exists(checkpoint.name):
os.remove(checkpoint.name)
except Exception as e:
print(f"An error occurred while attempting to delete the file: {e}")
@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(click_entrypoint, 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(click_entrypoint, 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;\nselect * from test limit 1;"
runner = CliRunner()
result = runner.invoke(click_entrypoint, 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_multiline_statement(executor):
run(executor, """create table test(a text)""")
run(executor, """insert into test values('abc'), ('def'), ('ghi')""")
sql = "select count(*)\nfrom test;\nselect * from test limit 1;"
runner = CliRunner()
result = runner.invoke(click_entrypoint, 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;\nselect * from test limit 1;"
runner = CliRunner()
result = runner.invoke(click_entrypoint, 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(click_entrypoint, 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_help_strings_end_with_periods():
"""Make sure click options have help text that end with a period."""
for param in click_entrypoint.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
socket = ''
def server_type(self):
return ["test"]
class TestPromptSession:
output = TestOutput()
app = None
m.prompt_session = TestPromptSession()
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, SQLResult())
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(monkeypatch):
"""Make sure that reserved space is returned as an integer."""
def stub_terminal_size():
return (5, 5)
with monkeypatch.context() as m:
m.setattr(shutil, "get_terminal_size", stub_terminal_size)
mycli = MyCli()
assert isinstance(mycli.get_reserved_space(), int)
def test_list_dsn(monkeypatch):
monkeypatch.setattr(MyCli, "system_config_files", [])
monkeypatch.setattr(MyCli, "pwd_config_file", os.devnull)
runner = CliRunner()
# keep Windows from locking the file with delete=False
with NamedTemporaryFile(prefix=TEMPFILE_PREFIX, mode="w", delete=False) as myclirc:
myclirc.write(
dedent("""\
[alias_dsn]
test = mysql://test/test
""")
)
myclirc.flush()
args = ["--list-dsn", "--myclirc", myclirc.name]
result = runner.invoke(click_entrypoint, args=args)
assert result.output == "test\n"
result = runner.invoke(click_entrypoint, args=args + ["--verbose"])
assert result.output == "test : mysql://test/test\n"
# delete=False means we should try to clean up
try:
if os.path.exists(myclirc.name):
os.remove(myclirc.name)
except Exception as e:
print(f"An error occurred while attempting to delete the file: {e}")
def test_list_ssh_config():
runner = CliRunner()
# keep Windows from locking the file with delete=False
with NamedTemporaryFile(prefix=TEMPFILE_PREFIX, mode="w", delete=False) 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(click_entrypoint, args=args)
assert "test\n" in result.output
result = runner.invoke(click_entrypoint, args=args + ["--verbose"])
assert "test : test.example.com\n" in result.output
# delete=False means we should try to clean up
try:
if os.path.exists(ssh_config.name):
os.remove(ssh_config.name)
except Exception as e:
print(f"An error occurred while attempting to delete the file: {e}")
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 = {
"main": {},
"alias_dsn": {},
"connection": {
"default_keepalive_ticks": 0,
},
}
def __init__(self, **args):
self.logger = Logger()
self.destructive_warning = False
self.main_formatter = Formatter()
self.redirect_formatter = Formatter()
self.ssl_mode = "auto"
self.my_cnf = {"client": {}, "mysqld": {}}
self.default_keepalive_ticks = 0
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.click_entrypoint, 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.click_entrypoint,
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 = {
"main": {},
"alias_dsn": {"test": "mysql://alias_dsn_user:alias_dsn_passwd@alias_dsn_host:4/alias_dsn_database"},
"connection": {
"default_keepalive_ticks": 0,
},
}
MockMyCli.connect_args = None
# When a user uses a DSN from the configuration file (alias_dsn),
# use these values.
result = runner.invoke(click_entrypoint, 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 = {
"main": {},
"alias_dsn": {"test": "mysql://alias_dsn_user:alias_dsn_passwd@alias_dsn_host:4/alias_dsn_database"},
"connection": {
"default_keepalive_ticks": 0,
},
}
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(
click_entrypoint,
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.click_entrypoint, 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"