-
Notifications
You must be signed in to change notification settings - Fork 695
Expand file tree
/
Copy pathtest_cli_runner.py
More file actions
365 lines (284 loc) · 12.9 KB
/
Copy pathtest_cli_runner.py
File metadata and controls
365 lines (284 loc) · 12.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
from __future__ import annotations
from types import SimpleNamespace
from typing import Any
import pytest
from mycli import cli_runner, main
class DummyLogger:
def __init__(self) -> None:
self.debug_calls: list[tuple[tuple[Any, ...], dict[str, Any]]] = []
def debug(self, *args: Any, **kwargs: Any) -> None:
self.debug_calls.append((args, kwargs))
class DummyMyCli:
def __init__(
self,
*,
config: dict[str, Any] | None = None,
my_cnf: dict[str, Any] | None = None,
config_without_package_defaults: dict[str, Any] | None = None,
) -> None:
self.config = config or default_config()
self.my_cnf = my_cnf or {'client': {}, 'mysqld': {}}
self.config_without_package_defaults = config_without_package_defaults or {}
self.default_keepalive_ticks = 5
self.ssl_mode: str | None = None
self.logger = DummyLogger()
self.dsn_alias: str | None = None
self.connect_calls: list[dict[str, Any]] = []
self.run_cli_called = False
self.close_called = False
def connect(self, **kwargs: Any) -> None:
self.connect_calls.append(dict(kwargs))
def run_cli(self) -> None:
self.run_cli_called = True
def close(self) -> None:
self.close_called = True
def default_config() -> dict[str, Any]:
return {
'main': {'use_keyring': 'false', 'my_cnf_transition_done': 'true'},
'connection': {'default_keepalive_ticks': 0},
'alias_dsn': {},
'init-commands': {},
'alias_dsn.init-commands': {},
}
def make_cli_args() -> main.CliArgs:
cli_args = main.CliArgs()
cli_args.format = None
cli_args.ssh_config_path = '/dev/null'
return cli_args
def run_with_client(
monkeypatch: pytest.MonkeyPatch,
cli_args: main.CliArgs,
client: DummyMyCli,
) -> DummyMyCli:
monkeypatch.setattr(main, 'preprocess_cli_args', lambda args, scheme_validator: 4)
monkeypatch.setattr(cli_runner.sys, 'stdin', SimpleNamespace(isatty=lambda: True))
monkeypatch.setattr(cli_runner.sys.stderr, 'isatty', lambda: False)
cli_runner.run_from_cli_args(cli_args, lambda **_kwargs: client)
return client
def test_expand_dsn_alias_env_var_returns_none() -> None:
assert cli_runner.expand_dsn_alias_env_var(None, 'prod') is None
def test_split_dsn_netloc_handles_user_without_password() -> None:
assert cli_runner.split_dsn_netloc('user@host:3306') == ('user', None, 'host', '3306')
def test_split_dsn_netloc_handles_empty_host() -> None:
assert cli_runner.split_dsn_netloc('user:pass@') == ('user', 'pass', None, None)
def test_split_dsn_netloc_handles_bracketed_ipv6_host() -> None:
assert cli_runner.split_dsn_netloc('user:pass@[::1]:3306') == ('user', 'pass', '::1', '3306')
def test_expand_dsn_alias_env_vars_rejects_non_integer_port(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv('MYCLI_TEST_DSN_PORT', 'not-an-int')
with pytest.raises(cli_runner.DsnAliasEnvVarError) as excinfo:
cli_runner.expand_dsn_alias_env_vars('mysql://user:pass@host:${MYCLI_TEST_DSN_PORT}/db', 'prod')
assert str(excinfo.value) == 'Port in DSN alias prod must be an integer.'
def test_run_from_cli_args_checkup_exits_zero(monkeypatch: pytest.MonkeyPatch) -> None:
cli_args = make_cli_args()
cli_args.checkup = True
client = DummyMyCli()
checkup_calls: list[DummyMyCli] = []
monkeypatch.setattr(cli_runner, 'main_checkup', lambda value: checkup_calls.append(value))
monkeypatch.setattr(main, 'preprocess_cli_args', lambda args, scheme_validator: 0)
with pytest.raises(SystemExit) as excinfo:
cli_runner.run_from_cli_args(cli_args, lambda **_kwargs: client)
assert excinfo.value.code == 0
assert checkup_calls == [client]
@pytest.mark.parametrize(
('csv', 'table', 'format_name', 'message'),
(
(True, False, 'table', 'Conflicting --csv and --format arguments.'),
(False, True, 'csv', 'Conflicting --table and --format arguments.'),
),
)
def test_run_from_cli_args_rejects_conflicting_format_flags(
monkeypatch: pytest.MonkeyPatch,
csv: bool,
table: bool,
format_name: str,
message: str,
) -> None:
cli_args = make_cli_args()
cli_args.csv = csv
cli_args.table = table
cli_args.format = format_name
secho_calls: list[tuple[str, dict[str, Any]]] = []
monkeypatch.setattr(cli_runner.click, 'secho', lambda text, **kwargs: secho_calls.append((text, kwargs)))
monkeypatch.setattr(main, 'preprocess_cli_args', lambda args, scheme_validator: 0)
with pytest.raises(SystemExit) as excinfo:
cli_runner.run_from_cli_args(cli_args, lambda **_kwargs: DummyMyCli())
assert excinfo.value.code == 1
assert secho_calls == [(message, {'err': True, 'fg': 'red'})]
def test_run_from_cli_args_treats_database_as_dsn_alias(monkeypatch: pytest.MonkeyPatch) -> None:
cli_args = make_cli_args()
cli_args.database = 'prod'
client = DummyMyCli(
config={
**default_config(),
'alias_dsn': {'prod': 'mysql://u:p@h/db'},
}
)
run_with_client(monkeypatch, cli_args, client)
assert client.dsn_alias == 'prod'
connect_call = client.connect_calls[-1]
assert connect_call['user'] == 'u'
assert connect_call['passwd'] == 'p'
assert connect_call['host'] == 'h'
assert connect_call['database'] == 'db'
def test_run_from_cli_args_leaves_dsn_alias_env_vars_disabled_by_default(
monkeypatch: pytest.MonkeyPatch,
) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'prod'
monkeypatch.setenv('MYCLI_TEST_DSN_USER', 'env_user')
client = DummyMyCli(
config={
**default_config(),
'alias_dsn': {'prod': 'mysql://${MYCLI_TEST_DSN_USER}:pass@host:3306/db'},
}
)
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['user'] == '${MYCLI_TEST_DSN_USER}'
def test_run_from_cli_args_expands_whole_dsn_alias_env_vars_when_enabled(
monkeypatch: pytest.MonkeyPatch,
) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'prod'
monkeypatch.setenv('MYCLI_TEST_DSN_USER', 'env_user')
monkeypatch.setenv('MYCLI_TEST_DSN_PASSWORD', 'env_pass')
monkeypatch.setenv('MYCLI_TEST_DSN_HOST', 'env-host')
monkeypatch.setenv('MYCLI_TEST_DSN_PORT', '3308')
monkeypatch.setenv('MYCLI_TEST_DSN_DATABASE', 'env_db')
monkeypatch.setenv('MYCLI_TEST_DSN_CHARSET', 'utf8mb4')
monkeypatch.setenv('MYCLI_TEST_DSN_KEEPALIVE', '9')
config = default_config()
config['main'] = {**config['main'], 'expand_dsn_alias_env_vars': 'true'}
config['alias_dsn'] = {
'prod': (
'mysql://${MYCLI_TEST_DSN_USER}:${MYCLI_TEST_DSN_PASSWORD}'
'@${MYCLI_TEST_DSN_HOST}:${MYCLI_TEST_DSN_PORT}/${MYCLI_TEST_DSN_DATABASE}'
'?character_set=${MYCLI_TEST_DSN_CHARSET}&keepalive_ticks=${MYCLI_TEST_DSN_KEEPALIVE}'
)
}
client = DummyMyCli(config=config)
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['user'] == 'env_user'
assert client.connect_calls[-1]['passwd'] == 'env_pass'
assert client.connect_calls[-1]['host'] == 'env-host'
assert client.connect_calls[-1]['port'] == 3308
assert client.connect_calls[-1]['database'] == 'env_db'
assert client.connect_calls[-1]['character_set'] == 'utf8mb4'
assert client.connect_calls[-1]['keepalive_ticks'] == 9
def test_run_from_cli_args_does_not_expand_partial_values_or_query_keys(
monkeypatch: pytest.MonkeyPatch,
) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'prod'
monkeypatch.setenv('MYCLI_TEST_DSN_USER', 'env_user')
monkeypatch.setenv('MYCLI_TEST_DSN_QUERY_KEY', 'character_set')
config = default_config()
config['main'] = {**config['main'], 'expand_dsn_alias_env_vars': 'true'}
config['alias_dsn'] = {
'prod': ('mysql://user-${MYCLI_TEST_DSN_USER}:pass@host:3306/db?${MYCLI_TEST_DSN_QUERY_KEY}=utf8mb4&character_set=utf8')
}
client = DummyMyCli(config=config)
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['user'] == 'user-${MYCLI_TEST_DSN_USER}'
assert client.connect_calls[-1]['character_set'] == 'utf8'
def test_run_from_cli_args_does_not_expand_unbraced_dsn_alias_env_vars(
monkeypatch: pytest.MonkeyPatch,
) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'prod'
monkeypatch.setenv('MYCLI_TEST_DSN_USER', 'env_user')
config = default_config()
config['main'] = {**config['main'], 'expand_dsn_alias_env_vars': 'true'}
config['alias_dsn'] = {'prod': 'mysql://$MYCLI_TEST_DSN_USER:pass@host:3306/db'}
client = DummyMyCli(config=config)
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['user'] == '$MYCLI_TEST_DSN_USER'
def test_run_from_cli_args_reports_missing_dsn_alias_env_var(
monkeypatch: pytest.MonkeyPatch,
) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'prod'
config = default_config()
config['main'] = {**config['main'], 'expand_dsn_alias_env_vars': 'true'}
config['alias_dsn'] = {'prod': 'mysql://${MYCLI_TEST_MISSING_DSN_USER}:pass@host:3306/db'}
client = DummyMyCli(config=config)
secho_calls: list[tuple[str, dict[str, Any]]] = []
monkeypatch.setattr(cli_runner.click, 'secho', lambda text, **kwargs: secho_calls.append((text, kwargs)))
with pytest.raises(SystemExit) as excinfo:
run_with_client(monkeypatch, cli_args, client)
assert excinfo.value.code == 1
assert secho_calls == [
(
'Environment variable MYCLI_TEST_MISSING_DSN_USER referenced by DSN alias prod is not set.',
{'err': True, 'fg': 'red'},
)
]
assert client.connect_calls == []
def test_run_from_cli_args_reports_missing_dsn(monkeypatch: pytest.MonkeyPatch) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'missing'
secho_calls: list[tuple[str, dict[str, Any]]] = []
monkeypatch.setattr(cli_runner, 'is_valid_connection_scheme', lambda value: (False, None))
monkeypatch.setattr(cli_runner.click, 'secho', lambda text, **kwargs: secho_calls.append((text, kwargs)))
monkeypatch.setattr(main, 'preprocess_cli_args', lambda args, scheme_validator: 0)
with pytest.raises(SystemExit) as excinfo:
cli_runner.run_from_cli_args(cli_args, lambda **_kwargs: DummyMyCli())
assert excinfo.value.code == 1
assert secho_calls == [
(
'Could not find the specified DSN in the config file. Please check the "[alias_dsn]" section in your myclirc.',
{'err': True, 'fg': 'red'},
)
]
def test_run_from_cli_args_maps_dsn_ssl_parameters(monkeypatch: pytest.MonkeyPatch) -> None:
cli_args = make_cli_args()
cli_args.dsn = (
'mysql://user:pass@host:3306/db?ssl=true&ssl_ca=~/ca.pem&ssl_capath=/capath'
'&ssl_cert=~/cert.pem&ssl_key=~/key.pem&ssl_cipher=AES256&tls_version=TLSv1.3'
'&ssl_verify_server_cert=true'
)
client = DummyMyCli()
secho_calls: list[str] = []
monkeypatch.setattr(cli_runner.click, 'secho', lambda text, **_kwargs: secho_calls.append(text))
run_with_client(monkeypatch, cli_args, client)
ssl = client.connect_calls[-1]['ssl']
assert ssl == {
'mode': 'on',
'ca': cli_runner.os.path.expanduser('~/ca.pem'),
'capath': '/capath',
'cert': cli_runner.os.path.expanduser('~/cert.pem'),
'key': cli_runner.os.path.expanduser('~/key.pem'),
'cipher': 'AES256',
'tls_version': 'TLSv1.3',
'check_hostname': True,
}
assert any('"ssl" DSN URI parameter is deprecated' in call for call in secho_calls)
def test_run_from_cli_args_merges_global_list_and_alias_scalar_init_commands(
monkeypatch: pytest.MonkeyPatch,
) -> None:
cli_args = make_cli_args()
cli_args.dsn = 'prod'
cli_args.init_command = 'set cli=1'
client = DummyMyCli(
config={
**default_config(),
'alias_dsn': {'prod': 'mysql://u:p@h/db'},
'init-commands': {'first': ['set global=1', 'set global=2']},
'alias_dsn.init-commands': {'prod': 'set alias=1'},
}
)
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['init_command'] == 'set global=1; set global=2; set alias=1; set cli=1'
def test_run_from_cli_args_resets_keyring(monkeypatch: pytest.MonkeyPatch) -> None:
cli_args = make_cli_args()
cli_args.use_keyring = 'reset'
client = DummyMyCli()
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['use_keyring'] is True
assert client.connect_calls[-1]['reset_keyring'] is True
def test_run_from_cli_args_uses_explicit_keyring_flag(monkeypatch: pytest.MonkeyPatch) -> None:
cli_args = make_cli_args()
cli_args.use_keyring = 'true'
client = DummyMyCli()
run_with_client(monkeypatch, cli_args, client)
assert client.connect_calls[-1]['use_keyring'] is True
assert client.connect_calls[-1]['reset_keyring'] is False