This repository was archived by the owner on Feb 20, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathtest_cli_ui.py
More file actions
421 lines (333 loc) · 11.7 KB
/
test_cli_ui.py
File metadata and controls
421 lines (333 loc) · 11.7 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
import datetime
import io
import os
import re
from typing import Iterator
from unittest import mock
import colorama
import colorama.ansi
import pytest
import cli_ui
from cli_ui.tests.conftest import MessageRecorder
BLUE = colorama.Fore.BLUE
GREEN = colorama.Fore.GREEN
RED = colorama.Fore.RED
RESET_ALL = colorama.Style.RESET_ALL
BRIGHT = colorama.Style.BRIGHT
class SmartTTY(io.StringIO):
def __init__(self) -> None:
super().__init__()
def isatty(self) -> bool:
return True
class DumbTTY(io.StringIO):
def __init__(self) -> None:
super().__init__()
def isatty(self) -> bool:
return False
@pytest.fixture
def smart_tty() -> SmartTTY:
return SmartTTY()
@pytest.fixture
def dumb_tty() -> DumbTTY:
return DumbTTY()
@pytest.fixture
def toggle_timestamp() -> Iterator[None]:
cli_ui.setup(timestamp=True)
yield
cli_ui.setup(timestamp=False)
@pytest.fixture
def always_color() -> Iterator[None]:
cli_ui.setup(color="always")
yield
cli_ui.setup(color="auto")
def test_info_with_colors(always_color: None, smart_tty: io.StringIO) -> None:
# fmt: off
cli_ui.info(
cli_ui.red, "this is red", cli_ui.reset,
cli_ui.green, "this is green",
fileobj=smart_tty
)
# fmt: on
expected = (
RED + "this is red " + RESET_ALL + GREEN + "this is green" + "\n" + RESET_ALL
)
actual = smart_tty.getvalue()
assert actual == expected
def test_update_title(always_color: None, smart_tty: SmartTTY) -> None:
# fmt: off
cli_ui.info(
"Something", cli_ui.bold, "bold",
fileobj=smart_tty,
update_title=True
)
expected = (
"\x1b]0;Something bold\n\x07"
f"Something {BRIGHT}bold\n{RESET_ALL}"
)
# fmt: on
actual = smart_tty.getvalue()
assert actual == expected
def test_info_stdout_no_colors(dumb_tty: DumbTTY) -> None:
# fmt: off
cli_ui.info(
cli_ui.red, "this is red", cli_ui.reset,
cli_ui.green, "this is green",
fileobj=dumb_tty
)
# fmt: on
expected = "this is red this is green\n"
actual = dumb_tty.getvalue()
assert actual == expected
def test_info_characters(always_color: None, smart_tty: SmartTTY) -> None:
cli_ui.info(
"Doing stuff", cli_ui.ellipsis, "success", cli_ui.check, fileobj=smart_tty
)
actual = smart_tty.getvalue()
if os.name == "nt":
success = "ok"
ellipsis = "..."
else:
success = "✓"
ellipsis = "…"
expected = f"Doing stuff {RESET_ALL}{RESET_ALL}{ellipsis} {RESET_ALL}success {RESET_ALL}{GREEN}{success} {RESET_ALL}\n{RESET_ALL}"
assert actual == expected
def test_timestamp(dumb_tty: DumbTTY, toggle_timestamp: None) -> None:
cli_ui.info("message", fileobj=dumb_tty)
actual = dumb_tty.getvalue()
match = re.match(r"\[(.*)\]", actual)
assert match
assert datetime.datetime.strptime(match.groups()[0], "%Y-%m-%d %H:%M:%S")
def test_table_with_lists_no_color(dumb_tty: DumbTTY) -> None:
headers = ["name", "score"]
data = [
[(cli_ui.bold, "John"), (cli_ui.green, 10)],
[(cli_ui.bold, "Jane"), (cli_ui.green, 5)],
]
cli_ui.info_table(data, headers=headers, fileobj=dumb_tty)
actual = dumb_tty.getvalue()
# fmt: off
expected = (
"name score\n"
"------ -------\n"
"John 10\n"
"Jane 5\n"
)
# fmt: on
assert actual == expected
def test_table_with_dict_no_color(dumb_tty: DumbTTY) -> None:
data = {
(cli_ui.bold, "Name"): [(cli_ui.green, "Alice"), (cli_ui.green, "Bob")],
(cli_ui.bold, "Age"): [(cli_ui.blue, 24), (cli_ui.blue, 9)],
}
cli_ui.info_table(data, headers="keys", fileobj=dumb_tty)
actual = dumb_tty.getvalue()
# fmt: off
expected = (
"Name Age\n"
"------ -----\n"
"Alice 24\n"
"Bob 9\n"
)
# fmt: on
assert actual == expected
def test_table_with_dict_and_color(always_color: None, smart_tty: SmartTTY) -> None:
data = {
(
cli_ui.bold,
"Name",
): [(cli_ui.green, "Alice"), (cli_ui.green, "Bob")],
(
cli_ui.bold,
"Age",
): [(cli_ui.blue, 24), (cli_ui.blue, 9)],
}
cli_ui.info_table(data, headers="keys", fileobj=smart_tty)
actual = smart_tty.getvalue()
# fmt: off
expected = (
f"{BRIGHT}Name{RESET_ALL} {BRIGHT}Age{RESET_ALL}\n"
"------ -----\n"
f"{GREEN}Alice{RESET_ALL} {BLUE}24{RESET_ALL}\n"
f"{GREEN}Bob{RESET_ALL} {BLUE}9{RESET_ALL}\n"
)
# fmt: on
assert actual == expected
def test_table_with_lists_with_color(always_color: None, smart_tty: SmartTTY) -> None:
headers = ["name", "score"]
data = [
[(cli_ui.bold, "John"), (cli_ui.green, 10)],
[(cli_ui.bold, "Jane"), (cli_ui.green, 5)],
]
cli_ui.info_table(data, headers=headers, fileobj=smart_tty)
actual = smart_tty.getvalue()
# fmt: off
expected = (
"name score\n"
"------ -------\n"
f"{BRIGHT}John{RESET_ALL} {GREEN}10{RESET_ALL}\n"
f"{BRIGHT}Jane{RESET_ALL} {GREEN}5{RESET_ALL}\n"
)
# fmt: on
assert actual == expected
def test_record_message(message_recorder: MessageRecorder) -> None:
cli_ui.info_1("This is foo")
assert message_recorder.find("foo")
message_recorder.reset()
cli_ui.info_1("This is bar")
assert not message_recorder.find("foo")
def test_read_input() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = ["foo"]
actual = cli_ui.read_input()
assert actual == "foo"
def test_read_password() -> None:
with mock.patch("getpass.getpass") as m:
m.side_effect = ["bar"]
actual = cli_ui.read_password()
assert actual == "bar"
def test_ask_string() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = ["sugar!", ""]
res = cli_ui.ask_string("coffee with what?")
assert res == "sugar!"
res = cli_ui.ask_string("coffee with what?", default="milk")
assert res == "milk"
def test_ask_colored_message() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = ["y"]
res = cli_ui.ask_yes_no(
"Deploy to", cli_ui.bold, "prod", cli_ui.reset, "?", default=False
)
assert res
def test_ask_password() -> None:
with mock.patch("getpass.getpass") as m:
m.side_effect = ["chocolate!", ""]
res = cli_ui.ask_password("guilty pleasure?")
assert res == "chocolate!"
def test_empty_password() -> None:
with mock.patch("getpass.getpass") as m:
m.side_effect = [""]
actual = cli_ui.ask_password(
"Please enter your password or just press enter to skip"
)
assert actual == ""
def test_ask_yes_no() -> None:
"""Test that you can answer with several types of common answers"""
with mock.patch("builtins.input") as m:
m.side_effect = ["y", "yes", "Yes", "n", "no", "No"]
expected_res = [True, True, True, False, False, False]
for res in expected_res:
actual = cli_ui.ask_yes_no("coffee?")
assert actual == res
def test_ask_yes_no_default() -> None:
"""Test that just pressing enter returns the default value"""
with mock.patch("builtins.input") as m:
m.side_effect = ["", ""]
assert cli_ui.ask_yes_no("coffee?", default=True) is True
assert cli_ui.ask_yes_no("coffee?", default=False) is False
def test_ask_yes_no_wrong_input() -> None:
"""Test that we keep asking when answer does not make sense"""
with mock.patch("builtins.input") as m:
m.side_effect = ["coffee!", "n"]
assert cli_ui.ask_yes_no("tea?") is False
assert m.call_count == 2
def test_ask_choice() -> None:
class Fruit:
def __init__(self, name: str, price: int):
self.name = name
self.price = price
def func_desc(fruit: Fruit) -> str:
return fruit.name
fruits = [Fruit("apple", 42), Fruit("banana", 10), Fruit("orange", 12)]
with mock.patch("builtins.input") as m:
m.side_effect = ["nan", "5", "2"]
actual = cli_ui.ask_choice(
"Select a fruit", choices=fruits, func_desc=func_desc
)
assert actual.name == "banana"
assert actual.price == 10
assert m.call_count == 3
def test_ask_choice_empty_input() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = [""]
res = cli_ui.ask_choice("Select a animal", choices=["cat", "dog", "cow"])
assert res is None
def test_ask_choice_ctrl_c() -> None:
with pytest.raises(KeyboardInterrupt):
with mock.patch("builtins.input") as m:
m.side_effect = KeyboardInterrupt
cli_ui.ask_choice("Select a animal", choices=["cat", "dog", "cow"])
def test_select_choices() -> None:
class Fruit:
def __init__(self, name: str, price: int):
self.name = name
self.price = price
def func_desc(fruit: Fruit) -> str:
return fruit.name
fruits = [Fruit("apple", 42), Fruit("banana", 10), Fruit("orange", 12)]
with mock.patch("builtins.input") as m:
m.side_effect = ["nan", "5", "1, 2"]
actual = cli_ui.select_choices(
"Select a fruit", choices=fruits, func_desc=func_desc
)
assert actual[0].name == "apple"
assert actual[0].price == 42
assert actual[1].name == "banana"
assert actual[1].price == 10
assert m.call_count == 3
def test_select_choices_empty_input() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = [""]
res = cli_ui.select_choices("Select a animal", choices=["cat", "dog", "cow"])
assert res is None
def test_select_choices_using_space_separator() -> None:
with mock.patch("builtins.input") as m:
m.side_effect = ["1 3"]
res = cli_ui.select_choices(
"Select a animal", choices=["cat", "dog", "cow"], sort=False
)
assert res == ["cat", "cow"]
def test_select_choices_ctrl_c() -> None:
with pytest.raises(KeyboardInterrupt):
with mock.patch("builtins.input") as m:
m.side_effect = KeyboardInterrupt
cli_ui.select_choices("Select a animal", choices=["cat", "dog", "cow"])
def test_quiet(message_recorder: MessageRecorder) -> None:
cli_ui.setup(quiet=True)
cli_ui.info("info")
cli_ui.error("error")
assert message_recorder.find("error")
assert not message_recorder.find("info")
def test_fatal() -> None:
cli_ui.setup(quiet=True)
with pytest.raises(SystemExit) as e:
cli_ui.fatal("default exit code")
assert e.value.code == 1
def test_fatal_with_custom_code() -> None:
cli_ui.setup(quiet=True)
with pytest.raises(SystemExit) as e:
cli_ui.fatal("custom exit code", exit_code=3)
assert e.value.code == 3
def test_color_always(dumb_tty: DumbTTY) -> None:
cli_ui.setup(color="always")
cli_ui.info(cli_ui.red, "this is red", fileobj=dumb_tty)
assert colorama.Fore.RED in dumb_tty.getvalue()
def test_color_never(smart_tty: SmartTTY) -> None:
cli_ui.setup(color="never")
cli_ui.info(cli_ui.red, "this is red", fileobj=smart_tty)
assert colorama.Fore.RED not in smart_tty.getvalue()
def test_message_for_exception(
message_recorder: MessageRecorder, dumb_tty: DumbTTY
) -> None:
def foo() -> None:
x = 1 / 0
print(x)
try:
foo()
except Exception as e:
error_message_tokens = cli_ui.message_for_exception(e, "error when fooing")
assert error_message_tokens[:3] == (
cli_ui.red,
"error when fooing\n",
"ZeroDivisionError",
)