Debian Codegraph @

tests/test_utils.py

raw symbols SCIP
1 """Unit testing for cmd2/utils.py module."""
2
3 import math
4 import os
5 import signal
6 import sys
7 import time
8 from unittest import (
9 mock,
10 )
11
12 import pytest
13
14 import cmd2.utils as cu
15
16 HELLO_WORLD = "Hello, world!"
17
18
19 def test_remove_duplicates_no_duplicates() -> None:
20 no_dups = [5, 4, 3, 2, 1]
21 assert cu.remove_duplicates(no_dups) == no_dups
22
23
24 def test_remove_duplicates_with_duplicates() -> None:
25 duplicates = [1, 1, 2, 3, 9, 9, 7, 8]
26 assert cu.remove_duplicates(duplicates) == [1, 2, 3, 9, 7, 8]
27
28
29 def test_alphabetical_sort() -> None:
30 my_list = ["café", "µ", "A", "micro", "unity", "cafeteria"]
31 assert cu.alphabetical_sort(my_list) == ["A", "cafeteria", "café", "micro", "unity", "µ"]
32 my_list = ["a3", "a22", "A2", "A11", "a1"]
33 assert cu.alphabetical_sort(my_list) == ["a1", "A11", "A2", "a22", "a3"]
34
35
36 def test_try_int_or_force_to_lower_case() -> None:
37 str1 = "17"
38 assert cu.try_int_or_force_to_lower_case(str1) == 17
39 str1 = "ABC"
40 assert cu.try_int_or_force_to_lower_case(str1) == "abc"
41 str1 = "X19"
42 assert cu.try_int_or_force_to_lower_case(str1) == "x19"
43 str1 = ""
44 assert cu.try_int_or_force_to_lower_case(str1) == ""
45
46
47 def test_natural_keys() -> None:
48 my_list = ["café", "µ", "A", "micro", "unity", "x1", "X2", "X11", "X0", "x22"]
49 my_list.sort(key=cu.natural_keys)
50 assert my_list == ["A", "café", "micro", "unity", "X0", "x1", "X2", "X11", "x22", "µ"]
51 my_list = ["a3", "a22", "A2", "A11", "a1"]
52 my_list.sort(key=cu.natural_keys)
53 assert my_list == ["a1", "A2", "a3", "A11", "a22"]
54
55
56 def test_natural_sort() -> None:
57 my_list = ["café", "µ", "A", "micro", "unity", "x1", "X2", "X11", "X0", "x22"]
58 assert cu.natural_sort(my_list) == ["A", "café", "micro", "unity", "X0", "x1", "X2", "X11", "x22", "µ"]
59 my_list = ["a3", "a22", "A2", "A11", "a1"]
60 assert cu.natural_sort(my_list) == ["a1", "A2", "a3", "A11", "a22"]
61
62
63 @pytest.fixture
64 def stdout_sim():
65 return cu.StdSim(sys.stdout, echo=True)
66
67
68 def test_stdsim_write_str(stdout_sim) -> None:
69 my_str = "Hello World"
70 stdout_sim.write(my_str)
71 assert stdout_sim.getvalue() == my_str
72
73
74 def test_stdsim_write_bytes(stdout_sim) -> None:
75 b_str = b"Hello World"
76 with pytest.raises(TypeError):
77 stdout_sim.write(b_str)
78
79
80 def test_stdsim_buffer_write_bytes(stdout_sim) -> None:
81 b_str = b"Hello World"
82 stdout_sim.buffer.write(b_str)
83 assert stdout_sim.getvalue() == b_str.decode()
84 assert stdout_sim.getbytes() == b_str
85
86
87 def test_stdsim_buffer_write_str(stdout_sim) -> None:
88 my_str = "Hello World"
89 with pytest.raises(TypeError):
90 stdout_sim.buffer.write(my_str)
91
92
93 def test_stdsim_read(stdout_sim) -> None:
94 my_str = "Hello World"
95 stdout_sim.write(my_str)
96 # getvalue() returns the value and leaves it unaffected internally
97 assert stdout_sim.getvalue() == my_str
98 # read() returns the value and then clears the internal buffer
99 assert stdout_sim.read() == my_str
100 assert stdout_sim.getvalue() == ""
101
102 stdout_sim.write(my_str)
103
104 assert stdout_sim.getvalue() == my_str
105 assert stdout_sim.read(2) == my_str[:2]
106 assert stdout_sim.getvalue() == my_str[2:]
107
108
109 def test_stdsim_read_bytes(stdout_sim) -> None:
110 b_str = b"Hello World"
111 stdout_sim.buffer.write(b_str)
112 # getbytes() returns the value and leaves it unaffected internally
113 assert stdout_sim.getbytes() == b_str
114 # read_bytes() returns the value and then clears the internal buffer
115 assert stdout_sim.readbytes() == b_str
116 assert stdout_sim.getbytes() == b""
117
118
119 def test_stdsim_clear(stdout_sim) -> None:
120 my_str = "Hello World"
121 stdout_sim.write(my_str)
122 assert stdout_sim.getvalue() == my_str
123 stdout_sim.clear()
124 assert stdout_sim.getvalue() == ""
125
126
127 def test_stdsim_getattr_exist(stdout_sim) -> None:
128 # Here the StdSim getattr is allowing us to access methods within StdSim
129 my_str = "Hello World"
130 stdout_sim.write(my_str)
131 val_func = stdout_sim.getvalue
132 assert val_func() == my_str
133
134
135 def test_stdsim_getattr_noexist(stdout_sim) -> None:
136 # Here the StdSim getattr is allowing us to access methods defined by the inner stream
137 assert not stdout_sim.isatty()
138
139
140 def test_stdsim_pause_storage(stdout_sim) -> None:
141 # Test pausing storage for string data
142 my_str = "Hello World"
143
144 stdout_sim.pause_storage = False
145 stdout_sim.write(my_str)
146 assert stdout_sim.read() == my_str
147
148 stdout_sim.pause_storage = True
149 stdout_sim.write(my_str)
150 assert stdout_sim.read() == ""
151
152 # Test pausing storage for binary data
153 b_str = b"Hello World"
154
155 stdout_sim.pause_storage = False
156 stdout_sim.buffer.write(b_str)
157 assert stdout_sim.readbytes() == b_str
158
159 stdout_sim.pause_storage = True
160 stdout_sim.buffer.write(b_str)
161 assert stdout_sim.getbytes() == b""
162
163
164 def test_stdsim_line_buffering(base_app) -> None:
165 # This exercises the case of writing binary data that contains new lines/carriage returns to a StdSim
166 # when line buffering is on. The output should immediately be flushed to the underlying stream.
167 import os
168 import tempfile
169
170 with tempfile.NamedTemporaryFile(mode="wt") as file:
171 file.line_buffering = True
172
173 stdsim = cu.StdSim(file, echo=True)
174 saved_size = os.path.getsize(file.name)
175
176 bytes_to_write = b"hello\n"
177 stdsim.buffer.write(bytes_to_write)
178 assert os.path.getsize(file.name) == saved_size + len(bytes_to_write)
179 saved_size = os.path.getsize(file.name)
180
181 bytes_to_write = b"hello\r"
182 stdsim.buffer.write(bytes_to_write)
183 assert os.path.getsize(file.name) == saved_size + len(bytes_to_write)
184
185
186 @pytest.fixture
187 def pr_none():
188 import subprocess
189
190 # Start a long running process so we have time to run tests on it before it finishes
191 # Put the new process into a separate group so its signal are isolated from ours
192 kwargs = {}
193 if sys.platform.startswith("win"):
194 command = "timeout -t 5 /nobreak"
195 kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
196 else:
197 command = "sleep 5"
198 kwargs["start_new_session"] = True
199
200 proc = subprocess.Popen(command, shell=True, **kwargs)
201 return cu.ProcReader(proc, None, None)
202
203
204 def test_proc_reader_send_sigint(pr_none) -> None:
205 assert pr_none._proc.poll() is None
206 pr_none.send_sigint()
207 pr_none.wait()
208 ret_code = pr_none._proc.poll()
209
210 # Make sure a SIGINT killed the process
211 if sys.platform.startswith("win"):
212 assert ret_code is not None
213 else:
214 assert ret_code == -signal.SIGINT
215
216
217 def test_proc_reader_terminate(pr_none) -> None:
218 assert pr_none._proc.poll() is None
219 pr_none.terminate()
220
221 wait_start = time.monotonic()
222 pr_none.wait()
223 wait_finish = time.monotonic()
224
225 # Make sure the process exited before sleep of 5 seconds finished
226 # 3 seconds accounts for some delay but is long enough for the process to exit
227 assert wait_finish - wait_start < 3
228
229 ret_code = pr_none._proc.poll()
230 if sys.platform.startswith("win"):
231 assert ret_code is not None
232 else:
233 assert ret_code == -signal.SIGTERM
234
235
236 @pytest.fixture
237 def context_flag():
238 return cu.ContextFlag()
239
240
241 def test_context_flag_bool(context_flag) -> None:
242 assert not context_flag
243 with context_flag:
244 assert context_flag
245
246
247 def test_context_flag_exit_err(context_flag) -> None:
248 with pytest.raises(ValueError, match="count has gone below 0"):
249 context_flag.__exit__()
250
251
252 def test_to_bool_str_true() -> None:
253 assert cu.to_bool("true")
254 assert cu.to_bool("True")
255 assert cu.to_bool("TRUE")
256 assert cu.to_bool("tRuE")
257
258
259 def test_to_bool_str_false() -> None:
260 assert not cu.to_bool("false")
261 assert not cu.to_bool("False")
262 assert not cu.to_bool("FALSE")
263 assert not cu.to_bool("fAlSe")
264
265
266 def test_to_bool_str_invalid() -> None:
267 with pytest.raises(ValueError): # noqa: PT011
268 cu.to_bool("other")
269
270
271 def test_to_bool_bool() -> None:
272 assert cu.to_bool(True)
273 assert not cu.to_bool(False)
274
275
276 def test_to_bool_int() -> None:
277 assert cu.to_bool(1)
278 assert cu.to_bool(-1)
279 assert not cu.to_bool(0)
280
281
282 def test_to_bool_float() -> None:
283 assert cu.to_bool(2.35)
284 assert cu.to_bool(0.25)
285 assert cu.to_bool(-math.pi)
286 assert not cu.to_bool(0)
287
288
289 def test_optional_int_none() -> None:
290 assert cu.optional_int(None) is None
291 assert cu.optional_int("none") is None
292 assert cu.optional_int("None") is None
293 assert cu.optional_int("nOnE") is None
294
295
296 def test_optional_int_int() -> None:
297 assert cu.optional_int(5) == 5
298 assert cu.optional_int("5") == 5
299 assert cu.optional_int("-10") == -10
300
301
302 def test_optional_int_invalid() -> None:
303 with pytest.raises(ValueError, match="must be an integer or None"):
304 cu.optional_int("abc")
305 with pytest.raises(ValueError, match="must be an integer or None"):
306 cu.optional_int("3.14")
307 with pytest.raises(ValueError, match="must be an integer or None"):
308 cu.optional_int([])
309
310
311 def test_find_editor_specified() -> None:
312 expected_editor = os.path.join("fake_dir", "editor")
313 with mock.patch.dict(os.environ, {"EDITOR": expected_editor}):
314 editor = cu.find_editor()
315 assert editor == expected_editor
316
317
318 def test_find_editor_not_specified() -> None:
319 # Use existing path env setting. Something in the editor list should be found.
320 editor = cu.find_editor()
321 assert editor
322
323 # Overwrite path env setting with invalid path, clear all other env vars so no editor should be found.
324 with mock.patch.dict(os.environ, {"PATH": "fake_dir"}, clear=True):
325 editor = cu.find_editor()
326 assert editor is None
327
328
329 def test_similarity() -> None:
330 suggested_command = cu.suggest_similar("comand", ["command", "UNRELATED", "NOT_SIMILAR"])
331 assert suggested_command == "command"
332 suggested_command = cu.suggest_similar("command", ["COMMAND", "acommands"])
333 assert suggested_command == "COMMAND"
334
335
336 def test_similarity_without_good_canididates() -> None:
337 suggested_command = cu.suggest_similar("comand", ["UNRELATED", "NOT_SIMILAR"])
338 assert suggested_command is None
339 suggested_command = cu.suggest_similar("comand", [])
340 assert suggested_command is None
341
342
343 def test_similarity_overwrite_function() -> None:
344 options = ["history", "test"]
345 suggested_command = cu.suggest_similar("test", options)
346 assert suggested_command == "test"
347
348 def custom_similarity_function(s1, s2) -> float:
349 return 1.0 if "history" in (s1, s2) else 0.0
350
351 suggested_command = cu.suggest_similar("test", options, similarity_function_to_use=custom_similarity_function)
352 assert suggested_command == "history"
353
354 suggested_command = cu.suggest_similar("history", options, similarity_function_to_use=custom_similarity_function)
355 assert suggested_command == "history"
356
357 suggested_command = cu.suggest_similar("test", ["test"], similarity_function_to_use=custom_similarity_function)
358 assert suggested_command is None
359
360
361 def test_get_types_invalid_input() -> None:
362 x = 1
363 with pytest.raises(ValueError, match="Argument passed to get_types should be a function or method"):
364 cu.get_types(x)
365
366
367 def test_get_types_empty() -> None:
368 def a(b):
369 print(b)
370
371 param_ann, ret_ann = cu.get_types(a)
372 assert ret_ann is None
373 assert param_ann == {}
374
375
376 def test_get_types_non_empty() -> None:
377 def foo(x: int) -> str:
378 return f"{x * x}"
379
380 param_ann, ret_ann = cu.get_types(foo)
381 assert ret_ann is str
382 param_name, param_value = next(iter(param_ann.items()))
383 assert param_name == "x"
384 assert param_value is int
385
386
387 def test_get_types_method() -> None:
388 class Foo:
389 def bar(self, x: bool) -> None:
390 print(x)
391
392 f = Foo()
393
394 param_ann, ret_ann = cu.get_types(f.bar)
395 assert ret_ann is None
396 assert len(param_ann) == 1
397 param_name, param_value = next(iter(param_ann.items()))
398 assert param_name == "x"
399 assert param_value is bool
400
401
402 def test_categorize() -> None:
403 from cmd2 import constants
404
405 category = "Test Category"
406 attr_name = constants.COMMAND_ATTR_HELP_CATEGORY
407
408 # Test single function
409 def func1() -> None:
410 pass
411
412 cu.categorize(func1, category)
413 assert getattr(func1, attr_name) == category
414
415 # Test single method
416 class Foo:
417 def foo_method(self) -> None:
418 pass
419
420 f = Foo()
421 cu.categorize(f.foo_method, category)
422 assert getattr(Foo.foo_method, attr_name) == category
423
424 # Test iterable
425 def func2() -> None:
426 pass
427
428 class Bar:
429 def bar_method(self) -> None:
430 pass
431
432 b = Bar()
433 cu.categorize([func2, b.bar_method], category)
434 assert getattr(func2, attr_name) == category
435 assert getattr(Bar.bar_method, attr_name) == category