Debian Codegraph @

tests/test_cmd2.py

raw symbols SCIP
1 """Cmd2 unit/functional testing"""
2
3 import io
4 import os
5 import signal
6 import sys
7 import tempfile
8 from code import InteractiveConsole
9 from typing import (
10 NoReturn,
11 cast,
12 )
13 from unittest import mock
14
15 import pytest
16 from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
17 from prompt_toolkit.completion import DummyCompleter
18 from prompt_toolkit.input import DummyInput, create_pipe_input
19 from prompt_toolkit.output import DummyOutput
20 from prompt_toolkit.shortcuts import PromptSession
21 from rich.style import Style
22 from rich.text import Text
23
24 import cmd2
25 from cmd2 import (
26 COMMAND_NAME,
27 Cmd2Style,
28 Color,
29 CommandSet,
30 Completions,
31 SubcommandRecord,
32 clipboard,
33 constants,
34 exceptions,
35 plugin,
36 stylize,
37 utils,
38 )
39 from cmd2 import rich_utils as ru
40 from cmd2 import string_utils as su
41 from cmd2.types import BoundCommandFunc
42
43 from .conftest import (
44 SHORTCUTS_TXT,
45 normalize,
46 odd_file_names,
47 run_cmd,
48 verify_help_text,
49 with_ansi_style,
50 )
51
52
53 def create_outsim_app():
54 c = cmd2.Cmd()
55 c.stdout = utils.StdSim(c.stdout)
56 return c
57
58
59 @pytest.fixture
60 def outsim_app():
61 return create_outsim_app()
62
63
64 def test_version(base_app) -> None:
65 assert cmd2.__version__
66
67
68 def test_complete_in_thread() -> None:
69 # Test default
70 app_default = cmd2.Cmd()
71 assert app_default.main_session.complete_in_thread is True
72
73 # Test True
74 app_true = cmd2.Cmd(complete_in_thread=True)
75 assert app_true.main_session.complete_in_thread is True
76
77 # Test False
78 app_false = cmd2.Cmd(complete_in_thread=False)
79 assert app_false.main_session.complete_in_thread is False
80
81
82 def test_not_in_main_thread(base_app, capsys) -> None:
83 import threading
84
85 # Mock threading.main_thread() to return our fake thread
86 saved_main_thread = threading.main_thread
87 fake_main = threading.Thread()
88 threading.main_thread = mock.MagicMock(name="main_thread", return_value=fake_main)
89
90 with pytest.raises(RuntimeError) as excinfo:
91 base_app.cmdloop()
92
93 # Restore threading.main_thread()
94 threading.main_thread = saved_main_thread
95 assert "cmdloop must be run in the main thread" in str(excinfo.value)
96
97
98 def test_empty_statement(base_app) -> None:
99 out, _err = run_cmd(base_app, "")
100 expected = normalize("")
101 assert out == expected
102
103
104 def test_base_help(base_app) -> None:
105 out, _err = run_cmd(base_app, "help")
106 assert base_app.last_result is True
107 verify_help_text(base_app, out)
108
109
110 def test_base_help_verbose(base_app) -> None:
111 out, _err = run_cmd(base_app, "help -v")
112 assert base_app.last_result is True
113 verify_help_text(base_app, out)
114
115 # Make sure :param type lines are filtered out of help summary
116 help_doc = base_app.do_help.__func__.__doc__
117 help_doc += "\n:param fake param"
118 base_app.do_help.__func__.__doc__ = help_doc
119
120 out, _err = run_cmd(base_app, "help --verbose")
121 assert base_app.last_result is True
122 verify_help_text(base_app, out)
123 assert ":param" not in "".join(out)
124
125
126 def test_base_argparse_help(base_app) -> None:
127 # Verify that "set -h" gives the same output as "help set" and that it starts in a way that makes sense
128 out1, _err1 = run_cmd(base_app, "set -h")
129 out2, _err2 = run_cmd(base_app, "help set")
130
131 assert out1 == out2
132 assert out1[0].startswith("Usage: set")
133 assert out1[1] == ""
134 assert out1[2].startswith("Set a settable parameter")
135
136
137 def test_base_invalid_option(base_app) -> None:
138 _out, err = run_cmd(base_app, "set -z")
139 assert err[0] == "Usage: set [-h] [param] [value]"
140 assert "Error: unrecognized arguments: -z" in err[1]
141
142
143 def test_base_shortcuts(base_app) -> None:
144 out, _err = run_cmd(base_app, "shortcuts")
145 expected = normalize(SHORTCUTS_TXT)
146 assert out == expected
147 assert base_app.last_result is True
148
149
150 def test_command_starts_with_shortcut() -> None:
151 expected_err = "Invalid command name 'help'"
152 with pytest.raises(ValueError, match=expected_err):
153 cmd2.Cmd(shortcuts={"help": "fake"})
154
155
156 def test_base_set(base_app) -> None:
157 # Make sure all settables appear in output.
158 out, _err = run_cmd(base_app, "set")
159 settables = sorted(base_app.settables.keys())
160
161 # The settables will appear in order in the table.
162 # Go line-by-line until all settables are found.
163 for line in out:
164 if not settables:
165 break
166 if line.lstrip().startswith(settables[0]):
167 settables.pop(0)
168
169 # This will be empty if we found all settables in the output.
170 assert not settables
171
172 # Make sure all settables appear in last_result.
173 assert len(base_app.last_result) == len(base_app.settables)
174 for param in base_app.last_result:
175 assert base_app.last_result[param] == base_app.settables[param].value
176
177
178 def test_set(base_app) -> None:
179 out, err = run_cmd(base_app, "set quiet True")
180 assert not out
181 assert base_app.last_result is True
182
183 # Test quiet respect
184 out, err = run_cmd(base_app, "set timing False")
185 assert not out
186 assert not err
187 assert base_app.last_result is True
188
189 # Show one settable (this always goes to out)
190 line_found = False
191 out, _err = run_cmd(base_app, "set quiet")
192 for line in out:
193 if "quiet" in line and "True" in line and "False" not in line:
194 line_found = True
195 break
196
197 assert line_found
198 assert len(base_app.last_result) == 1
199 assert base_app.last_result["quiet"] is True
200 base_app.quiet = False
201
202
203 def test_set_val_empty(base_app) -> None:
204 base_app.editor = "fake"
205 _out, _err = run_cmd(base_app, 'set editor ""')
206 assert base_app.editor == ""
207 assert base_app.last_result is True
208
209
210 def test_set_val_is_flag(base_app) -> None:
211 base_app.editor = "fake"
212 _out, _err = run_cmd(base_app, 'set editor "-h"')
213 assert base_app.editor == "-h"
214 assert base_app.last_result is True
215
216
217 def test_set_not_supported(base_app) -> None:
218 _out, err = run_cmd(base_app, "set qqq True")
219 expected = normalize(
220 """
221 Parameter 'qqq' not supported (type 'set' for list of parameters).
222 """
223 )
224 assert err == expected
225 assert base_app.last_result is False
226
227
228 def test_set_no_settables(base_app) -> None:
229 base_app._settables.clear()
230 _out, err = run_cmd(base_app, "set quiet True")
231 expected = normalize("There are no settable parameters")
232 assert err == expected
233 assert base_app.last_result is False
234
235
236 @pytest.mark.parametrize(
237 ("new_val", "is_valid", "expected"),
238 [
239 (ru.AllowStyle.NEVER, True, ru.AllowStyle.NEVER),
240 ("neVeR", True, ru.AllowStyle.NEVER),
241 (ru.AllowStyle.TERMINAL, True, ru.AllowStyle.TERMINAL),
242 ("TeRMInal", True, ru.AllowStyle.TERMINAL),
243 (ru.AllowStyle.ALWAYS, True, ru.AllowStyle.ALWAYS),
244 ("AlWaYs", True, ru.AllowStyle.ALWAYS),
245 ("invalid", False, ru.AllowStyle.TERMINAL),
246 ],
247 )
248 @with_ansi_style(ru.AllowStyle.TERMINAL)
249 def test_set_allow_style(base_app: cmd2.Cmd, new_val: str, is_valid: bool, expected: ru.AllowStyle) -> None:
250 from cmd2.pt_utils import pt_resolve_color_depth
251
252 # Use the set command to alter allow_style
253 out, err = run_cmd(base_app, f"set allow_style {new_val}")
254 assert base_app.last_result is is_valid
255
256 # Verify the results
257 assert expected == ru.ALLOW_STYLE
258 if is_valid:
259 assert out
260 assert not err
261 assert base_app.main_session.color_depth == pt_resolve_color_depth()
262
263
264 def test_set_traceback_show_locals(base_app: cmd2.Cmd) -> None:
265 """Test the set command for reading and setting traceback_show_locals."""
266 import inspect
267
268 from rich.traceback import Traceback
269
270 # Get Traceback's default value for "show_locals"
271 traceback_sig = inspect.signature(Traceback.__init__)
272 default_val = traceback_sig.parameters["show_locals"].default
273
274 # Clear any existing value
275 base_app.traceback_kwargs.pop("show_locals", None)
276 assert "show_locals" not in base_app.traceback_kwargs
277
278 # Test that we receive the default value if not present
279 orig_val = base_app.traceback_show_locals
280 assert orig_val is default_val
281 assert "show_locals" not in base_app.traceback_kwargs
282
283 # Test setting it
284 new_val = not orig_val
285 run_cmd(base_app, f"set traceback_show_locals {new_val}")
286 assert base_app.traceback_show_locals is new_val
287 assert base_app.traceback_kwargs["show_locals"] is new_val
288
289 # Test invalid input
290 _out, err = run_cmd(base_app, "set traceback_show_locals invalid")
291 assert base_app.last_result is False
292 assert "must be True or False (case-insensitive)" in err[0]
293
294
295 def test_set_traceback_width(base_app: cmd2.Cmd) -> None:
296 """Test the set command for reading and setting traceback_width."""
297
298 import inspect
299
300 from rich.traceback import Traceback
301
302 # Get Traceback's default value for "width"
303 traceback_sig = inspect.signature(Traceback.__init__)
304 default_val = traceback_sig.parameters["width"].default
305
306 # Clear any existing value
307 base_app.traceback_kwargs.pop("width", None)
308 assert "width" not in base_app.traceback_kwargs
309
310 # Test that we receive the default value if not present
311 orig_val = base_app.traceback_width
312 assert orig_val == default_val
313 assert "width" not in base_app.traceback_kwargs
314
315 # Test setting it to an integer (handling case where orig_val is None)
316 new_val = (orig_val or 0) + 100
317 run_cmd(base_app, f"set traceback_width {new_val}")
318 assert base_app.traceback_width == new_val
319 assert base_app.traceback_kwargs["width"] == new_val
320
321 # Test setting to "None" (case-insensitive)
322 run_cmd(base_app, "set traceback_width None")
323 assert base_app.traceback_width is None
324 assert base_app.traceback_kwargs["width"] is None # type: ignore[unreachable]
325
326 run_cmd(base_app, "set traceback_width none")
327 assert base_app.traceback_width is None
328
329 # Test invalid input
330 _out, err = run_cmd(base_app, "set traceback_width invalid")
331 assert base_app.last_result is False
332 assert "must be an integer or None" in err[0]
333
334
335 def test_set_with_choices(base_app) -> None:
336 """Test choices validation of Settables"""
337 fake_choices = ["valid", "choices"]
338 base_app.fake = fake_choices[0]
339
340 fake_settable = cmd2.Settable("fake", type(base_app.fake), "fake description", base_app, choices=fake_choices)
341 base_app.add_settable(fake_settable)
342
343 # Try a valid choice
344 out, err = run_cmd(base_app, f"set fake {fake_choices[1]}")
345 assert base_app.last_result is True
346 assert not err
347 assert out[0].startswith("fake")
348 assert out[0].endswith(f"─> {fake_choices[1]!r}")
349
350 # Try an invalid choice
351 _out, err = run_cmd(base_app, "set fake bad_value")
352 assert base_app.last_result is False
353 assert err[0].startswith("Error setting fake: invalid choice")
354
355
356 def test_set_with_rich_description(base_app) -> None:
357 """Test with rich Text description."""
358 description = "Rich text description"
359 base_app.rich_settable = "old"
360 rich_settable = cmd2.Settable(
361 "rich_settable", type(base_app.rich_settable), Text(description, Style(color="red", bold=True)), base_app
362 )
363 base_app.add_settable(rich_settable)
364
365 # Try see list settables info
366 out, err = run_cmd(base_app, "set rich_settable")
367 assert not err
368 name, value, text = out[-1].strip().split(maxsplit=2)
369 assert name == "rich_settable"
370 assert value == "old"
371 assert text == description
372
373 # Try to set a valid value
374 out, err = run_cmd(base_app, "set rich_settable new")
375 assert base_app.last_result is True
376 assert not err
377 assert out[0].startswith("rich_settable")
378 assert out[0].endswith("─> 'new'")
379
380
381 class OnChangeHookApp(cmd2.Cmd):
382 def __init__(self, *args, **kwargs) -> None:
383 super().__init__(*args, **kwargs)
384 self.add_settable(utils.Settable("quiet", bool, "my description", self, onchange_cb=self._onchange_quiet))
385
386 def _onchange_quiet(self, name, old, new) -> None:
387 """Runs when quiet is changed via set command"""
388 self.poutput("You changed " + name)
389
390
391 @pytest.fixture
392 def onchange_app():
393 return OnChangeHookApp()
394
395
396 def test_set_onchange_hook(onchange_app) -> None:
397 out, err = run_cmd(onchange_app, "set quiet True")
398 assert out == ["You changed quiet"]
399 # quiet: False -> True is not shown because quiet is now True
400 assert not err
401 assert onchange_app.last_result is True
402
403
404 def test_base_shell(base_app, monkeypatch) -> None:
405 m = mock.Mock()
406 monkeypatch.setattr("{}.Popen".format("subprocess"), m)
407 out, _err = run_cmd(base_app, "shell echo a")
408 assert out == []
409 assert m.called
410
411
412 def test_shell_last_result(base_app) -> None:
413 base_app.last_result = None
414 run_cmd(base_app, "shell fake")
415 assert base_app.last_result is not None
416
417
418 def test_shell_manual_call(base_app) -> None:
419 # Verifies crash from Issue #986 doesn't happen
420 cmds = ['echo "hi"', 'echo "there"', 'echo "cmd2!"']
421 cmd = ";".join(cmds)
422
423 base_app.do_shell(cmd)
424
425 cmd = "&&".join(cmds)
426
427 base_app.do_shell(cmd)
428
429
430 def test_base_error(base_app) -> None:
431 _out, err = run_cmd(base_app, "meow")
432 assert "is not a recognized command" in err[0]
433
434
435 def test_base_error_suggest_command(base_app) -> None:
436 try:
437 old_suggest_similar_command = base_app.suggest_similar_command
438 base_app.suggest_similar_command = True
439 _out, err = run_cmd(base_app, "historic")
440 assert "history" in err[1]
441 finally:
442 base_app.suggest_similar_command = old_suggest_similar_command
443
444
445 def test_run_script(base_app, request) -> None:
446 test_dir = os.path.dirname(request.module.__file__)
447 filename = os.path.join(test_dir, "script.txt")
448
449 assert base_app._script_dir == []
450 assert base_app._current_script_dir is None
451
452 # Get output out the script
453 script_out, script_err = run_cmd(base_app, f"run_script {filename}")
454 assert base_app.last_result is True
455
456 assert base_app._script_dir == []
457 assert base_app._current_script_dir is None
458
459 # Now run the commands manually and compare their output to script's
460 with open(filename, encoding="utf-8") as file:
461 script_commands = file.read().splitlines()
462
463 manual_out = []
464 manual_err = []
465 for cmdline in script_commands:
466 out, err = run_cmd(base_app, cmdline)
467 manual_out.extend(out)
468 manual_err.extend(err)
469
470 assert script_out == manual_out
471 assert script_err == manual_err
472
473
474 def test_run_script_with_empty_args(base_app) -> None:
475 _out, err = run_cmd(base_app, "run_script")
476 assert "the following arguments are required" in err[1]
477 assert base_app.last_result is None
478
479
480 def test_run_script_with_invalid_file(base_app, request) -> None:
481 # Path does not exist
482 _out, err = run_cmd(base_app, "run_script does_not_exist.txt")
483 assert "Problem accessing script from " in err[0]
484 assert base_app.last_result is False
485
486 # Path is a directory
487 test_dir = os.path.dirname(request.module.__file__)
488 _out, err = run_cmd(base_app, f"run_script {test_dir}")
489 assert "Problem accessing script from " in err[0]
490 assert base_app.last_result is False
491
492
493 def test_run_script_with_empty_file(base_app, request) -> None:
494 test_dir = os.path.dirname(request.module.__file__)
495 filename = os.path.join(test_dir, "scripts", "empty.txt")
496 out, err = run_cmd(base_app, f"run_script {filename}")
497 assert not out
498 assert not err
499 assert base_app.last_result is True
500
501
502 def test_run_script_with_binary_file(base_app, request) -> None:
503 test_dir = os.path.dirname(request.module.__file__)
504 filename = os.path.join(test_dir, "scripts", "binary.bin")
505 _out, err = run_cmd(base_app, f"run_script {filename}")
506 assert "is not an ASCII or UTF-8 encoded text file" in err[0]
507 assert base_app.last_result is False
508
509
510 def test_run_script_with_python_file(base_app, request, monkeypatch) -> None:
511 read_input_mock = mock.MagicMock(name="read_input", return_value="2")
512 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
513
514 test_dir = os.path.dirname(request.module.__file__)
515 filename = os.path.join(test_dir, "pyscript", "stop.py")
516 _out, err = run_cmd(base_app, f"run_script {filename}")
517 assert "appears to be a Python file" in err[0]
518 assert base_app.last_result is False
519
520
521 def test_run_script_with_utf8_file(base_app, request) -> None:
522 test_dir = os.path.dirname(request.module.__file__)
523 filename = os.path.join(test_dir, "scripts", "utf8.txt")
524
525 assert base_app._script_dir == []
526 assert base_app._current_script_dir is None
527
528 # Get output out the script
529 script_out, script_err = run_cmd(base_app, f"run_script {filename}")
530 assert base_app.last_result is True
531
532 assert base_app._script_dir == []
533 assert base_app._current_script_dir is None
534
535 # Now run the commands manually and compare their output to script's
536 with open(filename, encoding="utf-8") as file:
537 script_commands = file.read().splitlines()
538
539 manual_out = []
540 manual_err = []
541 for cmdline in script_commands:
542 out, err = run_cmd(base_app, cmdline)
543 manual_out.extend(out)
544 manual_err.extend(err)
545
546 assert script_out == manual_out
547 assert script_err == manual_err
548
549
550 def test_scripts_add_to_history(base_app, request) -> None:
551 test_dir = os.path.dirname(request.module.__file__)
552 filename = os.path.join(test_dir, "scripts", "help.txt")
553 command = f"run_script {filename}"
554
555 # Add to history
556 base_app.scripts_add_to_history = True
557 base_app.history.clear()
558 run_cmd(base_app, command)
559 assert len(base_app.history) == 2
560 assert base_app.history.get(1).raw == command
561 assert base_app.history.get(2).raw == "help -v"
562
563 # Do not add to history
564 base_app.scripts_add_to_history = False
565 base_app.history.clear()
566 run_cmd(base_app, command)
567 assert len(base_app.history) == 1
568 assert base_app.history.get(1).raw == command
569
570
571 def test_run_script_nested_run_scripts(base_app, request) -> None:
572 # Verify that running a script with nested run_script commands works correctly,
573 # and runs the nested script commands in the correct order.
574 test_dir = os.path.dirname(request.module.__file__)
575 filename = os.path.join(test_dir, "scripts", "nested.txt")
576
577 # Run the top level script
578 initial_run = "run_script " + filename
579 run_cmd(base_app, initial_run)
580 assert base_app.last_result is True
581
582 # Check that the right commands were executed.
583 expected = f"""
584 {initial_run}
585 _relative_run_script precmds.txt
586 set allow_style Always
587 help
588 shortcuts
589 _relative_run_script postcmds.txt
590 set allow_style Terminal"""
591 out, _err = run_cmd(base_app, "history -s")
592 assert out == normalize(expected)
593
594
595 def test_runcmds_plus_hooks(base_app, request) -> None:
596 test_dir = os.path.dirname(request.module.__file__)
597 prefilepath = os.path.join(test_dir, "scripts", "precmds.txt")
598 postfilepath = os.path.join(test_dir, "scripts", "postcmds.txt")
599
600 base_app.runcmds_plus_hooks(["run_script " + prefilepath, "help", "shortcuts", "run_script " + postfilepath])
601 expected = f"""
602 run_script {prefilepath}
603 set allow_style Always
604 help
605 shortcuts
606 run_script {postfilepath}
607 set allow_style Terminal"""
608
609 out, _err = run_cmd(base_app, "history -s")
610 assert out == normalize(expected)
611
612
613 def test_runcmds_plus_hooks_ctrl_c(base_app, capsys) -> None:
614 """Test Ctrl-C while in runcmds_plus_hooks"""
615 import types
616
617 def do_keyboard_interrupt(self, _) -> NoReturn:
618 raise KeyboardInterrupt("Interrupting this command")
619
620 base_app.do_keyboard_interrupt = types.MethodType(do_keyboard_interrupt, base_app)
621
622 # Default behavior is to not stop runcmds_plus_hooks() on Ctrl-C
623 base_app.history.clear()
624 base_app.runcmds_plus_hooks(["help", "keyboard_interrupt", "shortcuts"])
625 _out, err = capsys.readouterr()
626 assert not err
627 assert len(base_app.history) == 3
628
629 # Ctrl-C should stop runcmds_plus_hooks() in this case
630 base_app.history.clear()
631 base_app.runcmds_plus_hooks(["help", "keyboard_interrupt", "shortcuts"], stop_on_keyboard_interrupt=True)
632 _out, err = capsys.readouterr()
633 assert err.startswith("Interrupting this command")
634 assert len(base_app.history) == 2
635
636
637 def test_relative_run_script(base_app, request) -> None:
638 test_dir = os.path.dirname(request.module.__file__)
639 filename = os.path.join(test_dir, "script.txt")
640
641 assert base_app._script_dir == []
642 assert base_app._current_script_dir is None
643
644 # Get output out the script
645 script_out, script_err = run_cmd(base_app, f"_relative_run_script {filename}")
646 assert base_app.last_result is True
647
648 assert base_app._script_dir == []
649 assert base_app._current_script_dir is None
650
651 # Now run the commands manually and compare their output to script's
652 with open(filename, encoding="utf-8") as file:
653 script_commands = file.read().splitlines()
654
655 manual_out = []
656 manual_err = []
657 for cmdline in script_commands:
658 out, err = run_cmd(base_app, cmdline)
659 manual_out.extend(out)
660 manual_err.extend(err)
661
662 assert script_out == manual_out
663 assert script_err == manual_err
664
665
666 @pytest.mark.parametrize("file_name", odd_file_names)
667 def test_relative_run_script_with_odd_file_names(base_app, file_name, monkeypatch) -> None:
668 """Test file names with various patterns"""
669 # Mock out the do_run_script call to see what args are passed to it
670 run_script_mock = mock.MagicMock(name="do_run_script")
671 monkeypatch.setattr("cmd2.Cmd.do_run_script", run_script_mock)
672
673 run_cmd(base_app, f"_relative_run_script {su.quote(file_name)}")
674 run_script_mock.assert_called_once_with(su.quote(file_name))
675
676
677 def test_relative_run_script_requires_an_argument(base_app) -> None:
678 _out, err = run_cmd(base_app, "_relative_run_script")
679 assert "Error: the following arguments" in err[1]
680 assert base_app.last_result is None
681
682
683 def test_in_script(request) -> None:
684 class HookApp(cmd2.Cmd):
685 def __init__(self, *args, **kwargs) -> None:
686 super().__init__(*args, **kwargs)
687 self.register_cmdfinalization_hook(self.hook)
688
689 def hook(self: cmd2.Cmd, data: plugin.CommandFinalizationData) -> plugin.CommandFinalizationData:
690 if self.in_script():
691 self.poutput("WE ARE IN SCRIPT")
692 return data
693
694 hook_app = HookApp()
695 test_dir = os.path.dirname(request.module.__file__)
696 filename = os.path.join(test_dir, "script.txt")
697 out, _err = run_cmd(hook_app, f"run_script {filename}")
698
699 assert "WE ARE IN SCRIPT" in out[-1]
700
701
702 def test_system_exit_in_command(base_app, capsys) -> None:
703 """Test raising SystemExit in a command"""
704 import types
705
706 exit_code = 5
707
708 def do_system_exit(self, _) -> NoReturn:
709 raise SystemExit(exit_code)
710
711 base_app.do_system_exit = types.MethodType(do_system_exit, base_app)
712
713 stop = base_app.onecmd_plus_hooks("system_exit")
714 assert stop
715 assert base_app.exit_code == exit_code
716
717
718 def test_passthrough_exception_in_command(base_app) -> None:
719 """Test raising a PassThroughException in a command"""
720 import types
721
722 expected_err = "Pass me up"
723
724 def do_passthrough(self, _) -> NoReturn:
725 wrapped_ex = OSError(expected_err)
726 raise exceptions.PassThroughException(wrapped_ex=wrapped_ex)
727
728 base_app.do_passthrough = types.MethodType(do_passthrough, base_app)
729
730 with pytest.raises(OSError, match=expected_err):
731 base_app.onecmd_plus_hooks("passthrough")
732
733
734 class RedirectionApp(cmd2.Cmd):
735 def __init__(self, *args, **kwargs) -> None:
736 super().__init__(*args, **kwargs)
737
738 def do_print_output(self, _: str) -> None:
739 """Print output to sys.stdout and self.stdout."""
740
741 # Only data written to self.stdout is redirected.
742 # Therefore the print() call will not be.
743 print("print")
744 self.poutput("poutput")
745
746 def do_print_feedback(self, _: str) -> None:
747 """Call pfeedback."""
748 self.pfeedback("feedback")
749
750
751 @pytest.fixture
752 def redirection_app() -> RedirectionApp:
753 return RedirectionApp()
754
755
756 def test_output_redirection(redirection_app: RedirectionApp, capsys: pytest.CaptureFixture[str]) -> None:
757 """Verify that redirection captures data written to self.stdout and not sys.stdout."""
758 fd, filename = tempfile.mkstemp(prefix="cmd2_test", suffix=".txt")
759 os.close(fd)
760
761 try:
762 # Verify that writing to a file works
763 run_cmd(redirection_app, f"print_output > {filename}")
764
765 # Verify print() went to sys.stdout
766 out, _err = capsys.readouterr()
767 assert out == "print\n"
768
769 with open(filename) as f:
770 lines = f.read().splitlines()
771
772 # Only data written to self.stdout should be in the file
773 assert len(lines) == 1
774 assert lines[0] == "poutput"
775
776 # Verify that appending to a file also works
777 run_cmd(redirection_app, f"print_output >> {filename}")
778
779 out, _err = capsys.readouterr()
780 assert out == "print\n"
781
782 with open(filename) as f:
783 lines = f.read().splitlines()
784
785 assert len(lines) == 2
786 assert lines[0] == "poutput"
787 assert lines[1] == "poutput"
788 finally:
789 os.remove(filename)
790
791
792 def test_output_redirection_to_nonexistent_directory(redirection_app) -> None:
793 filename = "~/fakedir/this_does_not_exist.txt"
794
795 _out, err = run_cmd(redirection_app, f"print_output > {filename}")
796 assert "Failed to redirect" in err[0]
797
798 _out, err = run_cmd(redirection_app, f"print_output >> {filename}")
799 assert "Failed to redirect" in err[0]
800
801
802 def test_output_redirection_to_too_long_filename(redirection_app) -> None:
803 filename = (
804 "~/sdkfhksdjfhkjdshfkjsdhfkjsdhfkjdshfkjdshfkjshdfkhdsfkjhewfuihewiufhweiufhiweufhiuewhiuewhfiuwehfia"
805 "ewhfiuewhfiuewhfiuewhiuewhfiuewhfiuewfhiuwehewiufhewiuhfiweuhfiuwehfiuewfhiuwehiuewfhiuewhiewuhfiueh"
806 "fiuwefhewiuhewiufhewiufhewiufhewiufhewiufhewiufhewiufhewiuhewiufhewiufhewiuheiufhiuewheiwufhewiufheu"
807 "fheiufhieuwhfewiuhfeiufhiuewfhiuewheiwuhfiuewhfiuewhfeiuwfhewiufhiuewhiuewhfeiuwhfiuwehfuiwehfiuehie"
808 "whfieuwfhieufhiuewhfeiuwfhiuefhueiwhfw"
809 )
810
811 _out, err = run_cmd(redirection_app, f"print_output > {filename}")
812 assert "Failed to redirect" in err[0]
813
814 _out, err = run_cmd(redirection_app, f"print_output >> {filename}")
815 assert "Failed to redirect" in err[0]
816
817
818 def test_feedback(redirection_app) -> None:
819 f, filename = tempfile.mkstemp(prefix="cmd2_test", suffix=".txt")
820 os.close(f)
821
822 try:
823 run_cmd(redirection_app, f"print_feedback > {filename}")
824 with open(filename) as f:
825 content = f.read().splitlines()
826 assert "feedback" in content
827 finally:
828 os.remove(filename)
829
830
831 def test_disallow_redirection(redirection_app: RedirectionApp, capsys: pytest.CaptureFixture[str]) -> None:
832 # Set allow_redirection to False
833 redirection_app.allow_redirection = False
834
835 filename = "test_allow_redirect.txt"
836
837 # Verify output wasn't redirected
838 out, _err = run_cmd(redirection_app, f"print_output > {filename}")
839 assert "poutput" in out
840
841 # Verify that no file was created
842 assert not os.path.exists(filename)
843
844
845 def test_pipe_to_shell(redirection_app: RedirectionApp, capsys: pytest.CaptureFixture[str]) -> None:
846 out, err = run_cmd(redirection_app, "print_output | sort")
847
848 # Verify print() went to sys.stdout
849 captured = capsys.readouterr()
850 assert captured.out == "print\n"
851
852 # Verify only data written to self.stdout was piped
853 assert "print" not in out
854 assert "poutput" in out
855 assert not err
856
857
858 def test_pipe_to_shell_and_redirect(redirection_app) -> None:
859 filename = "out.txt"
860 out, err = run_cmd(redirection_app, f"print_output | sort > {filename}")
861 assert not out
862 assert not err
863 assert os.path.exists(filename)
864 os.remove(filename)
865
866
867 def test_pipe_to_shell_error(redirection_app) -> None:
868 # Try to pipe command output to a shell command that doesn't exist in order to produce an error
869 out, err = run_cmd(redirection_app, "print_output | foobarbaz.this_does_not_exist")
870 assert not out
871 assert "Pipe process exited with code" in err[0]
872
873
874 try:
875 # try getting the contents of the clipboard
876 _ = clipboard.get_paste_buffer()
877 # pyperclip raises at least the following types of exceptions
878 # FileNotFoundError on Windows Subsystem for Linux (WSL) when Windows paths are removed from $PATH
879 # ValueError for headless Linux systems without Gtk installed
880 # AssertionError can be raised by paste_klipper().
881 # PyperclipException for pyperclip-specific exceptions
882 except Exception: # noqa: BLE001
883 can_paste = False
884 else:
885 can_paste = True
886
887
888 @pytest.mark.skipif(not can_paste, reason="Pyperclip could not find a copy/paste mechanism for your system")
889 def test_send_to_paste_buffer(redirection_app: RedirectionApp, capsys: pytest.CaptureFixture[str]) -> None:
890 # Test writing to the PasteBuffer/Clipboard
891 run_cmd(redirection_app, "print_output >")
892
893 # Verify print() went to sys.stdout
894 out, _err = capsys.readouterr()
895 assert out == "print\n"
896
897 lines = cmd2.clipboard.get_paste_buffer().splitlines()
898 assert len(lines) == 1
899 assert lines[0] == "poutput"
900
901 # Test appending to the PasteBuffer/Clipboard
902 run_cmd(redirection_app, "print_output >>")
903
904 out, _err = capsys.readouterr()
905 assert out == "print\n"
906
907 lines = cmd2.clipboard.get_paste_buffer().splitlines()
908 assert len(lines) == 2
909 assert lines[0] == "poutput"
910 assert lines[1] == "poutput"
911
912
913 def test_get_paste_buffer_exception(redirection_app, mocker, capsys) -> None:
914 # Force get_paste_buffer to throw an exception
915 pastemock = mocker.patch("pyperclip.paste")
916 pastemock.side_effect = ValueError("foo")
917
918 # Redirect command output to the clipboard
919 redirection_app.onecmd_plus_hooks("print_output > ")
920
921 # Make sure we got the exception output
922 out, err = capsys.readouterr()
923 assert out == ""
924 # this just checks that cmd2 is surfacing whatever error gets raised by pyperclip.paste
925 assert "ValueError" in err
926 assert "foo" in err
927
928
929 def test_allow_clipboard_initializer(redirection_app) -> None:
930 assert redirection_app.allow_clipboard is True
931 noclipcmd = cmd2.Cmd(allow_clipboard=False)
932 assert noclipcmd.allow_clipboard is False
933
934
935 # if clipboard access is not allowed, cmd2 should check that first
936 # before it tries to do anything with pyperclip, that's why we can
937 # safely run this test without skipping it if pyperclip doesn't
938 # work in the test environment, like we do for test_send_to_paste_buffer()
939 def test_allow_clipboard(base_app) -> None:
940 base_app.allow_clipboard = False
941 out, err = run_cmd(base_app, "help >")
942 assert not out
943 assert "Clipboard access not allowed" in err
944
945
946 def test_base_timing(base_app) -> None:
947 out, err = run_cmd(base_app, "set timing True")
948 assert out[0].startswith("timing")
949 assert out[0].endswith("─> True")
950
951 if sys.platform == "win32":
952 assert err[0].startswith("Elapsed: 0:00:00")
953 else:
954 assert err[0].startswith("Elapsed: 0:00:00.0")
955
956
957 def test_base_debug(base_app) -> None:
958 # Purposely set the editor to None
959 base_app.editor = None
960
961 # Make sure we get an exception, but cmd2 handles it
962 out, err = run_cmd(base_app, "edit")
963 assert "ValueError: Please use 'set editor'" in err[0]
964 assert "To enable full traceback" in err[3]
965
966 # Set debug true
967 out, err = run_cmd(base_app, "set debug True")
968 assert not err
969 assert out[0].startswith("debug")
970 assert out[0].endswith("─> True")
971
972 # Verify that we now see the exception traceback
973 out, err = run_cmd(base_app, "edit")
974 assert "Traceback (most recent call last)" in err[0]
975
976
977 def test_debug_not_settable(base_app) -> None:
978 # Set debug to False and make it unsettable
979 base_app.debug = False
980 base_app.remove_settable("debug")
981
982 # Cause an exception by setting editor to None and running edit
983 base_app.editor = None
984 _out, err = run_cmd(base_app, "edit")
985
986 # Since debug is unsettable, the user will not be given the option to enable a full traceback
987 assert err == ["ValueError: Please use 'set editor' to specify your text editing program of", "choice."]
988
989
990 def test_blank_exception(mocker, base_app):
991 mocker.patch("cmd2.Cmd.do_help", side_effect=Exception)
992 _out, err = run_cmd(base_app, "help")
993
994 # When an exception has no message, the first error line is just its type.
995 assert err[0] == "Exception"
996
997
998 def test_remove_settable_keyerror(base_app) -> None:
999 with pytest.raises(KeyError):
1000 base_app.remove_settable("fake")
1001
1002
1003 def test_edit_file(base_app, request, monkeypatch) -> None:
1004 # Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
1005 base_app.editor = "fooedit"
1006
1007 # Mock out the subprocess.Popen call so we don't actually open an editor
1008 m = mock.MagicMock(name="Popen")
1009 monkeypatch.setattr("subprocess.Popen", m)
1010
1011 test_dir = os.path.dirname(request.module.__file__)
1012 filename = os.path.join(test_dir, "script.txt")
1013
1014 run_cmd(base_app, f"edit {filename}")
1015
1016 # We think we have an editor, so should expect a Popen call
1017 m.assert_called_once()
1018
1019
1020 @pytest.mark.parametrize("file_name", odd_file_names)
1021 def test_edit_file_with_odd_file_names(base_app, file_name, monkeypatch) -> None:
1022 """Test editor and file names with various patterns"""
1023 # Mock out the do_shell call to see what args are passed to it
1024 shell_mock = mock.MagicMock(name="do_shell")
1025 monkeypatch.setattr("cmd2.Cmd.do_shell", shell_mock)
1026
1027 base_app.editor = "fooedit"
1028 file_name = su.quote("nothingweird.py")
1029 run_cmd(base_app, f"edit {su.quote(file_name)}")
1030 shell_mock.assert_called_once_with(f'"fooedit" {su.quote(file_name)}')
1031
1032
1033 def test_edit_file_with_spaces(base_app, request, monkeypatch) -> None:
1034 # Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
1035 base_app.editor = "fooedit"
1036
1037 # Mock out the subprocess.Popen call so we don't actually open an editor
1038 m = mock.MagicMock(name="Popen")
1039 monkeypatch.setattr("subprocess.Popen", m)
1040
1041 test_dir = os.path.dirname(request.module.__file__)
1042 filename = os.path.join(test_dir, "my commands.txt")
1043
1044 run_cmd(base_app, f'edit "{filename}"')
1045
1046 # We think we have an editor, so should expect a Popen call
1047 m.assert_called_once()
1048
1049
1050 def test_edit_blank(base_app, monkeypatch) -> None:
1051 # Set a fake editor just to make sure we have one. We aren't really going to call it due to the mock
1052 base_app.editor = "fooedit"
1053
1054 # Mock out the subprocess.Popen call so we don't actually open an editor
1055 m = mock.MagicMock(name="Popen")
1056 monkeypatch.setattr("subprocess.Popen", m)
1057
1058 run_cmd(base_app, "edit")
1059
1060 # We have an editor, so should expect a Popen call
1061 m.assert_called_once()
1062
1063
1064 def test_base_py_interactive(base_app) -> None:
1065 # Mock out the InteractiveConsole.interact() call so we don't actually wait for a user's response on stdin
1066 m = mock.MagicMock(name="interact")
1067 InteractiveConsole.interact = m
1068
1069 run_cmd(base_app, "py")
1070
1071 # Make sure our mock was called once and only once
1072 m.assert_called_once()
1073
1074
1075 def test_base_cmdloop_with_startup_commands() -> None:
1076 intro = "Hello World, this is an intro ..."
1077
1078 # Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
1079 testargs = ["prog", "quit"]
1080 expected = intro + "\n"
1081
1082 with mock.patch.object(sys, "argv", testargs):
1083 app = create_outsim_app()
1084
1085 # Run the command loop with custom intro
1086 app.cmdloop(intro=intro)
1087
1088 out = app.stdout.getvalue()
1089 assert out == expected
1090
1091
1092 def test_base_cmdloop_without_startup_commands(monkeypatch) -> None:
1093 # Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
1094 testargs = ["prog"]
1095 with mock.patch.object(sys, "argv", testargs):
1096 app = create_outsim_app()
1097
1098 app.intro = "Hello World, this is an intro ..."
1099
1100 read_command_mock = mock.MagicMock(name="_read_command_line", return_value="quit")
1101 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
1102
1103 expected = app.intro + "\n"
1104
1105 # Run the command loop
1106 app.cmdloop()
1107 out = app.stdout.getvalue()
1108 assert out == expected
1109
1110
1111 def test_cmdfinalizations_runs(base_app, monkeypatch) -> None:
1112 """Make sure _run_cmdfinalization_hooks is run after each command."""
1113 with (
1114 mock.patch("sys.stdin.isatty", mock.MagicMock(name="isatty", return_value=True)),
1115 mock.patch("sys.stdin.fileno", mock.MagicMock(name="fileno", return_value=0)),
1116 ):
1117 monkeypatch.setattr(base_app.stdin, "fileno", lambda: 0)
1118 monkeypatch.setattr(base_app.stdin, "isatty", lambda: True)
1119
1120 cmd_fin = mock.MagicMock(name="cmdfinalization")
1121 monkeypatch.setattr("cmd2.Cmd._run_cmdfinalization_hooks", cmd_fin)
1122
1123 base_app.onecmd_plus_hooks("help")
1124 cmd_fin.assert_called_once()
1125
1126
1127 @pytest.mark.skipif(sys.platform.startswith("win"), reason="termios is not available on Windows")
1128 @pytest.mark.parametrize(
1129 ("is_tty", "settings_set", "raised_exception", "should_call"),
1130 [
1131 (True, True, None, True),
1132 (True, True, "termios_error", True),
1133 (True, True, "unsupported_operation", True),
1134 (False, True, None, False),
1135 (True, False, None, False),
1136 ],
1137 )
1138 def test_restore_termios_settings(base_app, monkeypatch, is_tty, settings_set, raised_exception, should_call):
1139 """Test that terminal settings are restored after a command and that errors are suppressed."""
1140 import io
1141 import termios # Mock termios since it's imported within the method
1142
1143 termios_mock = mock.MagicMock()
1144 # The error attribute needs to be the actual exception for isinstance checks
1145 termios_mock.error = termios.error
1146 monkeypatch.setitem(sys.modules, "termios", termios_mock)
1147
1148 # Set the exception to be raised by tcsetattr
1149 if raised_exception == "termios_error":
1150 termios_mock.tcsetattr.side_effect = termios.error("test termios error")
1151 elif raised_exception == "unsupported_operation":
1152 termios_mock.tcsetattr.side_effect = io.UnsupportedOperation("test io error")
1153
1154 # Set initial termios settings so the logic will run
1155 if settings_set:
1156 termios_settings = ["dummy settings"]
1157 base_app._initial_termios_settings = termios_settings
1158 else:
1159 base_app._initial_termios_settings = None
1160 termios_settings = None # for the assert
1161
1162 # Mock stdin to make it look like a TTY
1163 monkeypatch.setattr(base_app.stdin, "isatty", lambda: is_tty)
1164 monkeypatch.setattr(base_app.stdin, "fileno", lambda: 0)
1165
1166 # Run a command to trigger _run_cmdfinalization_hooks
1167 # This should not raise an exception
1168 base_app.onecmd_plus_hooks("help")
1169
1170 # Verify that tcsetattr was called with the correct arguments
1171 if should_call:
1172 termios_mock.tcsetattr.assert_called_once_with(0, termios_mock.TCSANOW, termios_settings)
1173 else:
1174 termios_mock.tcsetattr.assert_not_called()
1175
1176
1177 def test_sigint_handler(base_app) -> None:
1178 # No KeyboardInterrupt should be raised when using sigint_protection
1179 with base_app.sigint_protection:
1180 base_app.sigint_handler(signal.SIGINT, 1)
1181
1182 # Without sigint_protection, a KeyboardInterrupt is raised
1183 with pytest.raises(KeyboardInterrupt):
1184 base_app.sigint_handler(signal.SIGINT, 1)
1185
1186
1187 def test_raise_keyboard_interrupt(base_app) -> None:
1188 with pytest.raises(KeyboardInterrupt) as excinfo:
1189 base_app._raise_keyboard_interrupt()
1190 assert "Got a keyboard interrupt" in str(excinfo.value)
1191
1192
1193 @pytest.mark.skipif(sys.platform.startswith("win"), reason="SIGTERM only handled on Linux/Mac")
1194 def test_termination_signal_handler(base_app) -> None:
1195 with pytest.raises(SystemExit) as excinfo:
1196 base_app.termination_signal_handler(signal.SIGHUP, 1)
1197 assert excinfo.value.code == signal.SIGHUP + 128
1198
1199 with pytest.raises(SystemExit) as excinfo:
1200 base_app.termination_signal_handler(signal.SIGTERM, 1)
1201 assert excinfo.value.code == signal.SIGTERM + 128
1202
1203
1204 class HookFailureApp(cmd2.Cmd):
1205 def __init__(self, *args, **kwargs) -> None:
1206 super().__init__(*args, **kwargs)
1207 # register a postparsing hook method
1208 self.register_postparsing_hook(self.postparsing_precmd)
1209
1210 def postparsing_precmd(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData:
1211 """Simulate precmd hook failure."""
1212 data.stop = True
1213 return data
1214
1215
1216 @pytest.fixture
1217 def hook_failure():
1218 return HookFailureApp()
1219
1220
1221 def test_precmd_hook_success(base_app) -> None:
1222 out = base_app.onecmd_plus_hooks("help")
1223 assert out is False
1224
1225
1226 def test_precmd_hook_failure(hook_failure) -> None:
1227 out = hook_failure.onecmd_plus_hooks("help")
1228 assert out is True
1229
1230
1231 class SayApp(cmd2.Cmd):
1232 def __init__(self, *args, **kwargs) -> None:
1233 super().__init__(*args, **kwargs)
1234
1235 def do_say(self, arg) -> None:
1236 self.poutput(arg)
1237
1238
1239 @pytest.fixture
1240 def say_app():
1241 app = SayApp(allow_cli_args=False)
1242 app.stdout = utils.StdSim(app.stdout)
1243 return app
1244
1245
1246 def test_ctrl_c_at_prompt(say_app, monkeypatch) -> None:
1247 read_command_mock = mock.MagicMock(name="_read_command_line")
1248 read_command_mock.side_effect = ["say hello", KeyboardInterrupt(), "say goodbye", "quit"]
1249 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
1250
1251 say_app.cmdloop()
1252
1253 # And verify the expected output to stdout
1254 out = say_app.stdout.getvalue()
1255 assert out == "hello\n^C\ngoodbye\n"
1256
1257
1258 def test_ctrl_d_at_prompt(say_app, monkeypatch) -> None:
1259 read_command_mock = mock.MagicMock(name="_read_command_line")
1260 read_command_mock.side_effect = ["say hello", EOFError()]
1261 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
1262
1263 say_app.cmdloop()
1264
1265 # And verify the expected output to stdout
1266 out = say_app.stdout.getvalue()
1267 assert out == "hello\n\n"
1268
1269
1270 @pytest.mark.skipif(
1271 sys.platform.startswith("win"),
1272 reason="Don't have a real Windows console with how we are currently running tests in GitHub Actions",
1273 )
1274 @pytest.mark.parametrize(
1275 ("msg", "prompt", "is_stale"),
1276 [
1277 ("msg_text", None, False),
1278 ("msg_text", "new_prompt> ", False),
1279 ("msg_text", "new_prompt> ", True),
1280 (None, "new_prompt> ", False),
1281 (None, "new_prompt> ", True),
1282 # Blank prompt is acceptable
1283 ("msg_text", "", False),
1284 (None, "", False),
1285 ],
1286 )
1287 def test_async_alert(base_app: cmd2.Cmd, msg: str, prompt: str, is_stale: bool) -> None:
1288 import time
1289
1290 with (
1291 mock.patch("cmd2.cmd2.print_formatted_text") as mock_print,
1292 mock.patch("cmd2.cmd2.get_app") as mock_get_app,
1293 ):
1294 # Set up the chained mock: get_app() returns mock_app, which has invalidate()
1295 mock_app = mock.MagicMock()
1296 mock_get_app.return_value = mock_app
1297
1298 base_app.add_alert(msg=msg, prompt=prompt)
1299 alert = base_app._alert_queue[0]
1300
1301 # Stale means alert was created before the current prompt.
1302 if is_stale:
1303 # In the past
1304 alert.timestamp = 0.0
1305 else:
1306 # In the future
1307 alert.timestamp = time.monotonic() + 99999999
1308
1309 with create_pipe_input() as pipe_input:
1310 base_app.main_session = PromptSession(
1311 input=pipe_input,
1312 output=DummyOutput(),
1313 history=base_app.main_session.history,
1314 completer=base_app.main_session.completer,
1315 )
1316 pipe_input.send_text("quit\n")
1317
1318 base_app._cmdloop()
1319
1320 # If there was a message, patch_stdout handles the redraw (no invalidate)
1321 if msg:
1322 assert msg in str(mock_print.call_args_list[0])
1323 mock_app.invalidate.assert_not_called()
1324
1325 # If there's only a prompt update, we expect invalidate() only if not continuation/stale
1326 elif prompt is not None:
1327 if is_stale:
1328 mock_app.invalidate.assert_not_called()
1329 else:
1330 mock_app.invalidate.assert_called_once()
1331
1332 # The state of base_app.prompt should always be correct regardless of redraw
1333 if prompt is not None:
1334 if is_stale:
1335 assert base_app.prompt != prompt
1336 else:
1337 assert base_app.prompt == prompt
1338
1339
1340 @pytest.mark.skipif(
1341 sys.platform.startswith("win"),
1342 reason="Don't have a real Windows console with how we are currently running tests in GitHub Actions",
1343 )
1344 def test_async_alert_rich(base_app: cmd2.Cmd) -> None:
1345 from prompt_toolkit.formatted_text import ANSI
1346 from rich.table import Table
1347
1348 table = Table("Header")
1349 table.add_row("Value")
1350
1351 with (
1352 mock.patch("cmd2.cmd2.print_formatted_text") as mock_print,
1353 mock.patch("cmd2.cmd2.get_app") as mock_get_app,
1354 ):
1355 mock_app = mock.MagicMock()
1356 mock_get_app.return_value = mock_app
1357
1358 # Add alert with a Rich table
1359 base_app.add_alert(msg=table, soft_wrap=False)
1360
1361 with create_pipe_input() as pipe_input:
1362 base_app.main_session = PromptSession(
1363 input=pipe_input,
1364 output=DummyOutput(),
1365 history=base_app.main_session.history,
1366 completer=base_app.main_session.completer,
1367 )
1368 pipe_input.send_text("quit\n")
1369 base_app._cmdloop()
1370
1371 # Verify that print_formatted_text was called with a formatted ANSI object
1372 assert mock_print.called
1373 args, _kwargs = mock_print.call_args
1374 printed_arg = args[0]
1375 assert isinstance(printed_arg, ANSI)
1376
1377 # The printed text should contain our table values
1378 assert "Header" in printed_arg.value
1379 assert "Value" in printed_arg.value
1380
1381
1382 def test_add_alert(base_app: cmd2.Cmd) -> None:
1383 base_app._alert_queue.clear()
1384
1385 # Nothing is added when both are None
1386 base_app.add_alert(msg=None, prompt=None)
1387 assert not base_app._alert_queue
1388
1389 # Test that soft_wrap defaults to True
1390 base_app.add_alert(msg="Hello", prompt=None)
1391 last_alert = base_app._alert_queue[-1]
1392 assert last_alert.msg == "Hello"
1393 assert last_alert.soft_wrap is True
1394 assert last_alert.prompt is None
1395
1396 # Test that soft_wrap can be set to True
1397 base_app.add_alert(msg="Hello", soft_wrap=True, prompt=None)
1398 last_alert = base_app._alert_queue[-1]
1399 assert last_alert.msg == "Hello"
1400 assert last_alert.soft_wrap is True
1401 assert last_alert.prompt is None
1402
1403 # Test that soft_wrap can be set to False
1404 base_app.add_alert(msg="Hello", soft_wrap=False, prompt=None)
1405 last_alert = base_app._alert_queue[-1]
1406 assert last_alert.msg == "Hello"
1407 assert last_alert.soft_wrap is False
1408 assert last_alert.prompt is None
1409
1410 # Test only prompt
1411 base_app.add_alert(msg=None, prompt="prompt> ")
1412 last_alert = base_app._alert_queue[-1]
1413 assert last_alert.msg is None
1414 assert last_alert.soft_wrap is True
1415 assert last_alert.prompt == "prompt> "
1416
1417
1418 def test_visible_prompt() -> None:
1419 app = cmd2.Cmd()
1420
1421 # This prompt has nothing which needs to be stripped
1422 app.prompt = "(Cmd) "
1423 assert app.visible_prompt == app.prompt
1424 assert su.str_width(app.prompt) == len(app.prompt)
1425
1426 # This prompt has color which needs to be stripped
1427 color_prompt = stylize("InColor", style=Color.CYAN) + "> "
1428 app.prompt = color_prompt
1429 assert app.visible_prompt == "InColor> "
1430 assert su.str_width(app.prompt) == len("InColor> ")
1431
1432
1433 class HelpApp(cmd2.Cmd):
1434 """Class for testing custom help_* methods which override docstring help."""
1435
1436 DEFAULT_CATEGORY = "My Default Category."
1437 MISC_HEADER = "Various topics found here."
1438
1439 def __init__(self, *args, **kwargs) -> None:
1440 super().__init__(*args, **kwargs)
1441 self.doc_leader = "I now present you with a list of help topics."
1442
1443 def do_squat(self, arg) -> None:
1444 """This docstring help will never be shown because the help_squat method overrides it."""
1445
1446 def help_squat(self) -> None:
1447 self.stdout.write("This command does diddly squat...\n")
1448
1449 def do_edit(self, arg) -> None:
1450 """This overrides the edit command and does nothing."""
1451
1452 # This command has no help text
1453 def do_no_help(self, arg) -> None:
1454 pass
1455
1456 def do_multiline_docstr(self, arg) -> None:
1457 """This documentation
1458 is multiple lines
1459 and there are no
1460 tabs
1461 """
1462
1463 def help_physics(self):
1464 """A miscellaneous help topic."""
1465 self.poutput("Here is some help on physics.")
1466
1467 parser_cmd_parser = cmd2.Cmd2ArgumentParser(description="This is the description.")
1468
1469 @cmd2.with_argparser(parser_cmd_parser)
1470 def do_parser_cmd(self, args) -> None:
1471 """This is the docstring."""
1472
1473
1474 @pytest.fixture
1475 def help_app():
1476 return HelpApp()
1477
1478
1479 def test_help_headers(capsys) -> None:
1480 help_app = HelpApp()
1481 help_app.onecmd_plus_hooks("help")
1482 out, _err = capsys.readouterr()
1483
1484 assert help_app.doc_leader in out
1485 assert HelpApp.DEFAULT_CATEGORY in out
1486 assert HelpApp.MISC_HEADER in out
1487 assert help_app.last_result is True
1488
1489
1490 def test_custom_command_help(help_app) -> None:
1491 out, _err = run_cmd(help_app, "help squat")
1492 expected = normalize("This command does diddly squat...")
1493 assert out == expected
1494 assert help_app.last_result is True
1495
1496
1497 def test_custom_help_menu(help_app) -> None:
1498 out, _err = run_cmd(help_app, "help")
1499 verify_help_text(help_app, out)
1500 assert help_app.last_result is True
1501
1502
1503 def test_help_no_help(help_app) -> None:
1504 _out, err = run_cmd(help_app, "help no_help")
1505 assert err[0].startswith("No help on no_help")
1506 assert help_app.last_result is False
1507
1508
1509 def test_help_overridden_method(help_app) -> None:
1510 out, _err = run_cmd(help_app, "help edit")
1511 expected = normalize("This overrides the edit command and does nothing.")
1512 assert out == expected
1513 assert help_app.last_result is True
1514
1515
1516 def test_help_multiline_docstring(help_app) -> None:
1517 out, _err = run_cmd(help_app, "help multiline_docstr")
1518 expected = normalize("This documentation\nis multiple lines\nand there are no\ntabs")
1519 assert out == expected
1520 assert help_app.last_result is True
1521
1522
1523 def test_miscellaneous_help_topic(help_app) -> None:
1524 out, _err = run_cmd(help_app, "help physics")
1525 expected = normalize("Here is some help on physics.")
1526 assert out == expected
1527 assert help_app.last_result is True
1528
1529
1530 def test_help_verbose(help_app: HelpApp) -> None:
1531 out, _err = run_cmd(help_app, "help --verbose")
1532 expected_verbose = utils.strip_doc_annotations(help_app.do_parser_cmd.__doc__)
1533 verify_help_text(help_app, out, verbose_strings=[expected_verbose])
1534
1535
1536 def test_help_verbose_with_fake_command(capsys) -> None:
1537 """Verify that only actual command functions appear in verbose output."""
1538 help_app = HelpApp()
1539
1540 cmds = ["alias", "fake_command"]
1541 help_app._print_documented_command_topics(help_app.DEFAULT_CATEGORY, cmds, verbose=True)
1542 out, _err = capsys.readouterr()
1543 assert cmds[0] in out
1544 assert cmds[1] not in out
1545
1546
1547 def test_render_columns_no_strs(help_app: HelpApp) -> None:
1548 no_strs = []
1549 result = help_app.render_columns(no_strs)
1550 assert result == ""
1551
1552
1553 def test_render_columns_one_str(help_app: HelpApp) -> None:
1554 one_str = ["one_string"]
1555 result = help_app.render_columns(one_str)
1556 assert result == "one_string"
1557
1558
1559 def test_render_columns_too_wide(help_app: HelpApp) -> None:
1560 commands = ["kind_of_long_string", "a_slightly_longer_string"]
1561 result = help_app.render_columns(commands, display_width=10)
1562
1563 expected = "kind_of_long_string \na_slightly_longer_string"
1564 assert result == expected
1565
1566
1567 def test_columnize(capsys: pytest.CaptureFixture[str]) -> None:
1568 help_app = HelpApp()
1569 items = ["one", "two"]
1570 help_app.columnize(items)
1571 out, _err = capsys.readouterr()
1572
1573 # poutput() adds a newline at the end.
1574 expected = "one two\n"
1575 assert out == expected
1576
1577
1578 class HelpCategoriesApp(cmd2.Cmd):
1579 """Class for testing custom help_* methods which override docstring help."""
1580
1581 SOME_CATEGORY = "Some Category"
1582 CUSTOM_CATEGORY = "Custom Category"
1583
1584 def __init__(self, *args, **kwargs) -> None:
1585 super().__init__(*args, **kwargs)
1586
1587 @cmd2.with_category("Some Category")
1588 def do_diddly(self, arg) -> None:
1589 """This command does diddly"""
1590
1591 # This command will be in the "Some Category" section of the help menu even though it has no docstring
1592 @cmd2.with_category(SOME_CATEGORY)
1593 def do_cat_nodoc(self, arg) -> None:
1594 pass
1595
1596 # This command will show in the category labeled with DEFAULT_CATEGORY
1597 def do_squat(self, arg) -> None:
1598 """This docstring help will never be shown because the help_squat method overrides it."""
1599
1600 def help_squat(self) -> None:
1601 self.stdout.write("This command does diddly squat...\n")
1602
1603 def do_edit(self, arg) -> None:
1604 """This overrides the edit command and does nothing."""
1605
1606 cmd2.categorize((do_squat, do_edit), CUSTOM_CATEGORY)
1607
1608
1609 @pytest.fixture
1610 def helpcat_app():
1611 return HelpCategoriesApp()
1612
1613
1614 def test_help_cat_base(helpcat_app) -> None:
1615 out, _err = run_cmd(helpcat_app, "help")
1616 assert helpcat_app.last_result is True
1617 verify_help_text(helpcat_app, out)
1618
1619 help_text = "".join(out)
1620 assert helpcat_app.CUSTOM_CATEGORY in help_text
1621 assert helpcat_app.SOME_CATEGORY in help_text
1622 assert helpcat_app.DEFAULT_CATEGORY in help_text
1623
1624
1625 def test_help_cat_verbose(helpcat_app) -> None:
1626 out, _err = run_cmd(helpcat_app, "help --verbose")
1627 assert helpcat_app.last_result is True
1628 verify_help_text(helpcat_app, out)
1629
1630 help_text = "".join(out)
1631 assert helpcat_app.CUSTOM_CATEGORY in help_text
1632 assert helpcat_app.SOME_CATEGORY in help_text
1633 assert helpcat_app.DEFAULT_CATEGORY in help_text
1634
1635
1636 class SelectApp(cmd2.Cmd):
1637 def do_eat(self, arg) -> None:
1638 """Eat something, with a selection of sauces to choose from."""
1639 # Pass in a single string of space-separated selections
1640 sauce = self.select("sweet salty", "Sauce? ")
1641 result = "{food} with {sauce} sauce, yum!"
1642 result = result.format(food=arg, sauce=sauce)
1643 self.stdout.write(result + "\n")
1644
1645 def do_study(self, arg) -> None:
1646 """Learn something, with a selection of subjects to choose from."""
1647 # Pass in a list of strings for selections
1648 subject = self.select(["math", "science"], "Subject? ")
1649 result = f"Good luck learning {subject}!\n"
1650 self.stdout.write(result)
1651
1652 def do_procrastinate(self, arg) -> None:
1653 """Waste time in your manner of choice."""
1654 # Pass in a list of tuples for selections
1655 leisure_activity = self.select(
1656 [("Netflix and chill", "Netflix"), ("YouTube", "WebSurfing")], "How would you like to procrastinate? "
1657 )
1658 result = f"Have fun procrasinating with {leisure_activity}!\n"
1659 self.stdout.write(result)
1660
1661 def do_play(self, arg) -> None:
1662 """Play your favorite musical instrument."""
1663 # Pass in an uneven list of tuples for selections
1664 instrument = self.select([("Guitar", "Electric Guitar"), ("Drums",)], "Instrument? ")
1665 result = f"Charm us with the {instrument}...\n"
1666 self.stdout.write(result)
1667
1668 def do_return_type(self, arg) -> None:
1669 """Test that return values can be non-strings"""
1670 choice = self.select([(1, "Integer"), ("test_str", "String"), (self.do_play, "Method")], "Choice? ")
1671 result = f"The return type is {type(choice)}\n"
1672 self.stdout.write(result)
1673
1674
1675 @pytest.fixture
1676 def select_app():
1677 return SelectApp()
1678
1679
1680 def test_select_options(select_app, monkeypatch) -> None:
1681 read_input_mock = mock.MagicMock(name="read_input", return_value="2")
1682 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1683
1684 food = "bacon"
1685 out, _err = run_cmd(select_app, f"eat {food}")
1686 expected = normalize(
1687 f"""
1688 1. sweet
1689 2. salty
1690 {food} with salty sauce, yum!
1691 """
1692 )
1693
1694 # Make sure our mock was called with the expected arguments
1695 read_input_mock.assert_called_once_with("Sauce? ")
1696
1697 # And verify the expected output to stdout
1698 assert out == expected
1699
1700
1701 def test_select_invalid_option_too_big(select_app, monkeypatch) -> None:
1702 read_input_mock = mock.MagicMock(name="read_input")
1703
1704 # If side_effect is an iterable then each call to the mock will return the next value from the iterable.
1705 read_input_mock.side_effect = ["3", "1"] # First pass an invalid selection, then pass a valid one
1706 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1707
1708 food = "fish"
1709 out, _err = run_cmd(select_app, f"eat {food}")
1710 expected = normalize(
1711 f"""
1712 1. sweet
1713 2. salty
1714 '3' isn't a valid choice. Pick a number between 1 and 2:
1715 {food} with sweet sauce, yum!
1716 """
1717 )
1718
1719 # Make sure our mock was called exactly twice with the expected arguments
1720 arg = "Sauce? "
1721 calls = [mock.call(arg), mock.call(arg)]
1722 read_input_mock.assert_has_calls(calls)
1723 assert read_input_mock.call_count == 2
1724
1725 # And verify the expected output to stdout
1726 assert out == expected
1727
1728
1729 def test_select_invalid_option_too_small(select_app, monkeypatch) -> None:
1730 read_input_mock = mock.MagicMock(name="read_input")
1731
1732 # If side_effect is an iterable then each call to the mock will return the next value from the iterable.
1733 read_input_mock.side_effect = ["0", "1"] # First pass an invalid selection, then pass a valid one
1734 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1735
1736 food = "fish"
1737 out, _err = run_cmd(select_app, f"eat {food}")
1738 expected = normalize(
1739 f"""
1740 1. sweet
1741 2. salty
1742 '0' isn't a valid choice. Pick a number between 1 and 2:
1743 {food} with sweet sauce, yum!
1744 """
1745 )
1746
1747 # Make sure our mock was called exactly twice with the expected arguments
1748 arg = "Sauce? "
1749 calls = [mock.call(arg), mock.call(arg)]
1750 read_input_mock.assert_has_calls(calls)
1751 assert read_input_mock.call_count == 2
1752
1753 # And verify the expected output to stdout
1754 assert out == expected
1755
1756
1757 def test_select_list_of_strings(select_app, monkeypatch) -> None:
1758 read_input_mock = mock.MagicMock(name="read_input", return_value="2")
1759 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1760
1761 out, _err = run_cmd(select_app, "study")
1762 expected = normalize(
1763 """
1764 1. math
1765 2. science
1766 Good luck learning {}!
1767 """.format("science")
1768 )
1769
1770 # Make sure our mock was called with the expected arguments
1771 read_input_mock.assert_called_once_with("Subject? ")
1772
1773 # And verify the expected output to stdout
1774 assert out == expected
1775
1776
1777 def test_select_list_of_tuples(select_app, monkeypatch) -> None:
1778 read_input_mock = mock.MagicMock(name="read_input", return_value="2")
1779 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1780
1781 out, _err = run_cmd(select_app, "procrastinate")
1782 expected = normalize(
1783 """
1784 1. Netflix
1785 2. WebSurfing
1786 Have fun procrasinating with {}!
1787 """.format("YouTube")
1788 )
1789
1790 # Make sure our mock was called with the expected arguments
1791 read_input_mock.assert_called_once_with("How would you like to procrastinate? ")
1792
1793 # And verify the expected output to stdout
1794 assert out == expected
1795
1796
1797 def test_select_uneven_list_of_tuples(select_app, monkeypatch) -> None:
1798 read_input_mock = mock.MagicMock(name="read_input", return_value="2")
1799 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1800
1801 out, _err = run_cmd(select_app, "play")
1802 expected = normalize(
1803 """
1804 1. Electric Guitar
1805 2. Drums
1806 Charm us with the {}...
1807 """.format("Drums")
1808 )
1809
1810 # Make sure our mock was called with the expected arguments
1811 read_input_mock.assert_called_once_with("Instrument? ")
1812
1813 # And verify the expected output to stdout
1814 assert out == expected
1815
1816
1817 @pytest.mark.parametrize(
1818 ("selection", "type_str"),
1819 [
1820 ("1", "<class 'int'>"),
1821 ("2", "<class 'str'>"),
1822 ("3", "<class 'method'>"),
1823 ],
1824 )
1825 def test_select_return_type(select_app, monkeypatch, selection, type_str) -> None:
1826 read_input_mock = mock.MagicMock(name="read_input", return_value=selection)
1827 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1828
1829 out, _err = run_cmd(select_app, "return_type")
1830 expected = normalize(
1831 f"""
1832 1. Integer
1833 2. String
1834 3. Method
1835 The return type is {type_str}
1836 """
1837 )
1838
1839 # Make sure our mock was called with the expected arguments
1840 read_input_mock.assert_called_once_with("Choice? ")
1841
1842 # And verify the expected output to stdout
1843 assert out == expected
1844
1845
1846 def test_select_eof(select_app, monkeypatch) -> None:
1847 # Ctrl-D during select causes an EOFError that just reprompts the user
1848 read_input_mock = mock.MagicMock(name="read_input", side_effect=[EOFError, 2])
1849 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1850
1851 food = "fish"
1852 _out, _err = run_cmd(select_app, f"eat {food}")
1853
1854 # Make sure our mock was called exactly twice with the expected arguments
1855 arg = "Sauce? "
1856 calls = [mock.call(arg), mock.call(arg)]
1857 read_input_mock.assert_has_calls(calls)
1858 assert read_input_mock.call_count == 2
1859
1860
1861 def test_select_ctrl_c(outsim_app, monkeypatch) -> None:
1862 # Ctrl-C during select prints ^C and raises a KeyboardInterrupt
1863 read_input_mock = mock.MagicMock(name="read_input", side_effect=KeyboardInterrupt)
1864 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1865
1866 with pytest.raises(KeyboardInterrupt):
1867 outsim_app.select([("Guitar", "Electric Guitar"), ("Drums",)], "Instrument? ")
1868
1869 out = outsim_app.stdout.getvalue()
1870 assert out.rstrip().endswith("^C")
1871
1872
1873 def test_select_choice_tty(outsim_app, monkeypatch) -> None:
1874 # Mock choice to return the first option
1875 choice_mock = mock.MagicMock(name="choice", return_value="sweet")
1876 monkeypatch.setattr("cmd2.cmd2.choice", choice_mock)
1877
1878 prompt = "Sauce? "
1879 options = ["sweet", "salty"]
1880
1881 with create_pipe_input() as pipe_input:
1882 outsim_app.main_session = PromptSession(
1883 input=pipe_input,
1884 output=DummyOutput(),
1885 )
1886
1887 result = outsim_app.select(options, prompt)
1888
1889 assert result == "sweet"
1890 choice_mock.assert_called_once_with(message=prompt, options=[("sweet", "sweet"), ("salty", "salty")])
1891
1892
1893 def test_select_choice_tty_ctrl_c(outsim_app, monkeypatch) -> None:
1894 # Mock choice to raise KeyboardInterrupt
1895 choice_mock = mock.MagicMock(name="choice", side_effect=KeyboardInterrupt)
1896 monkeypatch.setattr("cmd2.cmd2.choice", choice_mock)
1897
1898 prompt = "Sauce? "
1899 options = ["sweet", "salty"]
1900
1901 # Mock isatty to be True for both stdin and stdout
1902 with create_pipe_input() as pipe_input:
1903 outsim_app.main_session = PromptSession(
1904 input=pipe_input,
1905 output=DummyOutput(),
1906 )
1907
1908 with pytest.raises(KeyboardInterrupt):
1909 outsim_app.select(options, prompt)
1910
1911 out = outsim_app.stdout.getvalue()
1912 assert out.rstrip().endswith("^C")
1913
1914
1915 def test_select_uneven_tuples_labels(outsim_app, monkeypatch) -> None:
1916 # Test that uneven tuples still work and labels are handled correctly
1917 # Case 1: (value, label) - normal
1918 # Case 2: (value,) - label should be value
1919 # Case 3: (value, None) - label should be value
1920 options = [("v1", "l1"), ("v2",), ("v3", None)]
1921
1922 # Mock read_input to return '1'
1923 read_input_mock = mock.MagicMock(name="read_input", return_value="1")
1924 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1925
1926 result = outsim_app.select(options, "Choice? ")
1927 assert result == "v1"
1928
1929 out = outsim_app.stdout.getvalue()
1930 assert "1. l1" in out
1931 assert "2. v2" in out
1932 assert "3. v3" in out
1933
1934
1935 def test_select_indexable_no_len(outsim_app, monkeypatch) -> None:
1936 # Test that an object with __getitem__ but no __len__ works.
1937 # This covers the except (IndexError, TypeError) block in select()
1938 class IndexableNoLen:
1939 def __getitem__(self, item: int) -> str:
1940 if item == 0:
1941 return "value"
1942 raise IndexError
1943
1944 # Mock read_input to return '1'
1945 read_input_mock = mock.MagicMock(name="read_input", return_value="1")
1946 monkeypatch.setattr("cmd2.Cmd.read_input", read_input_mock)
1947
1948 options = [IndexableNoLen()]
1949 result = outsim_app.select(options, "Choice? ")
1950 assert result == "value"
1951
1952 out = outsim_app.stdout.getvalue()
1953 assert "1. value" in out
1954
1955
1956 class HelpNoDocstringApp(cmd2.Cmd):
1957 greet_parser = cmd2.Cmd2ArgumentParser()
1958 greet_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE")
1959
1960 @cmd2.with_argparser(greet_parser, with_unknown_args=True)
1961 def do_greet(self, opts, arg) -> None:
1962 arg = "".join(arg)
1963 if opts.shout:
1964 arg = arg.upper()
1965 self.stdout.write(arg + "\n")
1966
1967
1968 def test_help_with_no_docstring(capsys) -> None:
1969 app = HelpNoDocstringApp()
1970 app.onecmd_plus_hooks("greet -h")
1971 out, err = capsys.readouterr()
1972 assert err == ""
1973 assert (
1974 out
1975 == """Usage: greet [-h] [-s]
1976
1977 Options:
1978 -h, --help show this help message and exit
1979 -s, --shout N00B EMULATION MODE
1980
1981 """
1982 )
1983
1984
1985 class MultilineApp(cmd2.Cmd):
1986 def __init__(self, *args, **kwargs) -> None:
1987 super().__init__(*args, multiline_commands=["orate"], **kwargs)
1988
1989 orate_parser = cmd2.Cmd2ArgumentParser()
1990 orate_parser.add_argument("-s", "--shout", action="store_true", help="N00B EMULATION MODE")
1991
1992 @cmd2.with_argparser(orate_parser, with_unknown_args=True)
1993 def do_orate(self, opts, arg) -> None:
1994 arg = "".join(arg)
1995 if opts.shout:
1996 arg = arg.upper()
1997 self.stdout.write(arg + "\n")
1998
1999
2000 @pytest.fixture
2001 def multiline_app():
2002 return MultilineApp()
2003
2004
2005 def test_multiline_complete_empty_statement_raises_exception(multiline_app) -> None:
2006 with pytest.raises(exceptions.EmptyStatement):
2007 multiline_app._complete_statement("")
2008
2009
2010 def test_multiline_complete_statement_without_terminator(multiline_app, monkeypatch) -> None:
2011 read_command_mock = mock.MagicMock(name="_read_command_line", return_value="\n")
2012 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
2013
2014 command = "orate"
2015 args = "hello world"
2016 line = f"{command} {args}"
2017 statement = multiline_app._complete_statement(line)
2018 assert statement == args
2019 assert statement.command == command
2020 assert statement.multiline_command
2021
2022
2023 def test_multiline_complete_statement_with_unclosed_quotes(multiline_app, monkeypatch) -> None:
2024 read_command_mock = mock.MagicMock(name="_read_command_line", side_effect=["quotes", '" now closed;'])
2025 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
2026
2027 line = 'orate hi "partially open'
2028 statement = multiline_app._complete_statement(line)
2029 assert statement == 'hi "partially open\nquotes\n" now closed'
2030 assert statement.command == "orate"
2031 assert statement.multiline_command
2032 assert statement.terminator == ";"
2033
2034
2035 def test_multiline_input_line_to_statement(multiline_app, monkeypatch) -> None:
2036 # Verify _input_line_to_statement saves the fully entered input line for multiline commands
2037 read_command_mock = mock.MagicMock(name="_read_command_line", side_effect=["person", "\n"])
2038 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
2039
2040 line = "orate hi"
2041 statement = multiline_app._input_line_to_statement(line)
2042 assert statement.raw == "orate hi\nperson\n\n"
2043 assert statement == "hi person"
2044 assert statement.command == "orate"
2045 assert statement.multiline_command
2046
2047
2048 def test_multiline_history_added(multiline_app, monkeypatch) -> None:
2049 # Test that multiline commands are added to history as a single item
2050 run_cmd(multiline_app, "history --clear")
2051
2052 read_command_mock = mock.MagicMock(name="_read_command_line", side_effect=["person", "\n"])
2053 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
2054
2055 # run_cmd calls onecmd_plus_hooks which triggers history addition
2056 run_cmd(multiline_app, "orate hi")
2057
2058 assert len(multiline_app.history) == 1
2059 assert multiline_app.history.get(1).raw == "orate hi\nperson\n\n"
2060
2061
2062 def test_multiline_history_with_quotes(multiline_app, monkeypatch) -> None:
2063 # Test combined multiline command with quotes is added to history correctly
2064 run_cmd(multiline_app, "history --clear")
2065
2066 read_command_mock = mock.MagicMock(name="_read_command_line", side_effect=[" and spaces ", ' "', " in", "quotes.", ";"])
2067 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
2068
2069 line = 'orate Look, "There are newlines'
2070 run_cmd(multiline_app, line)
2071
2072 assert len(multiline_app.history) == 1
2073 history_item = multiline_app.history.get(1)
2074 history_lines = history_item.raw.splitlines()
2075 assert history_lines[0] == 'orate Look, "There are newlines'
2076 assert history_lines[1] == " and spaces "
2077 assert history_lines[2] == ' "'
2078 assert history_lines[3] == " in"
2079 assert history_lines[4] == "quotes."
2080 assert history_lines[5] == ";"
2081
2082
2083 def test_multiline_complete_statement_eof(multiline_app, monkeypatch):
2084 # Mock poutput to verify it's called
2085 poutput_mock = mock.MagicMock(name="poutput")
2086 monkeypatch.setattr(multiline_app, "poutput", poutput_mock)
2087
2088 read_raw_mock = mock.MagicMock(name="_read_raw_input", side_effect=EOFError)
2089 monkeypatch.setattr("cmd2.Cmd._read_raw_input", read_raw_mock)
2090
2091 command = "orate"
2092 args = "hello world"
2093 line = f"{command} {args}"
2094
2095 # This should call _read_command_line, get 'eof', set nextline to '\n',
2096 # and then parse the line with the newline terminator.
2097 statement = multiline_app._complete_statement(line)
2098
2099 assert statement.command == command
2100 assert statement.args == args
2101 assert statement.terminator == "\n"
2102
2103 # Verify that poutput('\n') was called
2104 poutput_mock.assert_called_once_with("\n")
2105
2106
2107 class CommandResultApp(cmd2.Cmd):
2108 def __init__(self, *args, **kwargs) -> None:
2109 super().__init__(*args, **kwargs)
2110
2111 def do_affirmative(self, arg) -> None:
2112 self.last_result = cmd2.CommandResult(arg, data=True)
2113
2114 def do_negative(self, arg) -> None:
2115 self.last_result = cmd2.CommandResult(arg, data=False)
2116
2117 def do_affirmative_no_data(self, arg) -> None:
2118 self.last_result = cmd2.CommandResult(arg)
2119
2120 def do_negative_no_data(self, arg) -> None:
2121 self.last_result = cmd2.CommandResult("", arg)
2122
2123
2124 @pytest.fixture
2125 def commandresult_app():
2126 return CommandResultApp()
2127
2128
2129 def test_commandresult_truthy(commandresult_app) -> None:
2130 arg = "foo"
2131 run_cmd(commandresult_app, f"affirmative {arg}")
2132 assert commandresult_app.last_result
2133 assert commandresult_app.last_result == cmd2.CommandResult(arg, data=True)
2134
2135 run_cmd(commandresult_app, f"affirmative_no_data {arg}")
2136 assert commandresult_app.last_result
2137 assert commandresult_app.last_result == cmd2.CommandResult(arg)
2138
2139
2140 def test_commandresult_falsy(commandresult_app) -> None:
2141 arg = "bar"
2142 run_cmd(commandresult_app, f"negative {arg}")
2143 assert not commandresult_app.last_result
2144 assert commandresult_app.last_result == cmd2.CommandResult(arg, data=False)
2145
2146 run_cmd(commandresult_app, f"negative_no_data {arg}")
2147 assert not commandresult_app.last_result
2148 assert commandresult_app.last_result == cmd2.CommandResult("", arg)
2149
2150
2151 @pytest.mark.skipif(sys.platform.startswith("win"), reason="Test is problematic on GitHub Actions Windows runners")
2152 def test_is_text_file_bad_input(base_app) -> None:
2153 # Test with a non-existent file
2154 with pytest.raises(FileNotFoundError):
2155 utils.is_text_file("does_not_exist.txt")
2156
2157 # Test with a directory
2158 with pytest.raises(IsADirectoryError):
2159 utils.is_text_file(".")
2160
2161
2162 def test__eof(base_app) -> None:
2163 base_app.do_quit = mock.MagicMock(return_value=True)
2164 assert base_app.do__eof("")
2165 base_app.do_quit.assert_called_once_with("")
2166
2167
2168 def test_quit(base_app) -> None:
2169 assert base_app.do_quit("")
2170 assert base_app.last_result is True
2171
2172
2173 def test_echo(capsys) -> None:
2174 app = cmd2.Cmd()
2175 app.echo = True
2176 commands = ["help history"]
2177
2178 app.runcmds_plus_hooks(commands)
2179
2180 out, _err = capsys.readouterr()
2181 assert out.startswith(f"{app.prompt}{commands[0]}\nUsage: history")
2182
2183
2184 @pytest.mark.skipif(
2185 sys.platform.startswith("win"),
2186 reason="Don't have a real Windows console with how we are currently running tests in GitHub Actions",
2187 )
2188 def test_read_raw_input_tty(base_app: cmd2.Cmd) -> None:
2189 with create_pipe_input() as pipe_input:
2190 base_app.main_session = PromptSession(
2191 input=pipe_input,
2192 output=DummyOutput(),
2193 history=base_app.main_session.history,
2194 completer=base_app.main_session.completer,
2195 )
2196 pipe_input.send_text("foo\n")
2197
2198 result = base_app._read_raw_input("prompt> ", base_app.main_session)
2199 assert result == "foo"
2200
2201
2202 def test_read_raw_input_interactive_pipe(capsys) -> None:
2203 prompt = "prompt> "
2204 app = cmd2.Cmd(stdin=io.StringIO("input from pipe\n"))
2205 app.interactive_pipe = True
2206 result = app._read_raw_input(prompt, app.main_session)
2207 assert result == "input from pipe"
2208
2209 # In interactive mode, _read_raw_input() prints the prompt.
2210 captured = capsys.readouterr()
2211 assert captured.out == prompt
2212
2213
2214 def test_read_raw_input_non_interactive_pipe_echo_off(capsys) -> None:
2215 prompt = "prompt> "
2216 app = cmd2.Cmd(stdin=io.StringIO("input from pipe\n"))
2217 app.interactive_pipe = False
2218 app.echo = False
2219 result = app._read_raw_input(prompt, app.main_session)
2220 assert result == "input from pipe"
2221
2222 # When not echoing in non-interactive mode, _read_raw_input() prints nothing.
2223 captured = capsys.readouterr()
2224 assert not captured.out
2225
2226
2227 def test_read_raw_input_non_interactive_pipe_echo_on(capsys) -> None:
2228 prompt = "prompt> "
2229 app = cmd2.Cmd(stdin=io.StringIO("input from pipe\n"))
2230 app.interactive_pipe = False
2231 app.echo = True
2232 result = app._read_raw_input(prompt, app.main_session)
2233 assert result == "input from pipe"
2234
2235 # When echoing in non-interactive mode, _read_raw_input() prints the prompt and input text.
2236 captured = capsys.readouterr()
2237 assert f"{prompt}input from pipe\n" == captured.out
2238
2239
2240 def test_read_raw_input_eof() -> None:
2241 app = cmd2.Cmd(stdin=io.StringIO(""))
2242 with pytest.raises(EOFError):
2243 app._read_raw_input("prompt> ", app.main_session)
2244
2245
2246 def test_resolve_completer_none(base_app: cmd2.Cmd) -> None:
2247 completer = base_app._resolve_completer()
2248 assert isinstance(completer, DummyCompleter)
2249
2250
2251 def test_resolve_completer_with_choices(base_app: cmd2.Cmd) -> None:
2252 from cmd2.pt_utils import Cmd2Completer
2253
2254 choices = ["apple", "banana", "cherry"]
2255 completer = base_app._resolve_completer(choices=choices)
2256 assert isinstance(completer, Cmd2Completer)
2257
2258 # Verify contents
2259 settings = completer.custom_settings
2260 assert settings is not None
2261
2262 action = settings.parser._actions[-1]
2263 assert action.choices == choices
2264 assert not settings.preserve_quotes
2265
2266
2267 def test_resolve_completer_with_choices_provider(base_app: cmd2.Cmd) -> None:
2268 from cmd2.pt_utils import Cmd2Completer
2269
2270 mock_provider = mock.MagicMock()
2271 completer = base_app._resolve_completer(choices_provider=mock_provider)
2272 assert isinstance(completer, Cmd2Completer)
2273
2274 # Verify contents
2275 settings = completer.custom_settings
2276 assert settings is not None
2277
2278 action = settings.parser._actions[-1]
2279 assert action.get_choices_provider() == mock_provider
2280 assert not settings.preserve_quotes
2281
2282
2283 def test_resolve_completer_with_completer(base_app: cmd2.Cmd) -> None:
2284 """Verify that providing choices creates a Cmd2Completer with a generated parser."""
2285 from cmd2.pt_utils import Cmd2Completer
2286
2287 mock_completer = mock.MagicMock()
2288 completer = base_app._resolve_completer(completer=mock_completer)
2289 assert isinstance(completer, Cmd2Completer)
2290
2291 # Verify contents
2292 settings = completer.custom_settings
2293 assert settings is not None
2294
2295 action = settings.parser._actions[-1]
2296 assert action.get_completer() == mock_completer
2297 assert not settings.preserve_quotes
2298
2299
2300 def test_resolve_completer_with_parser(base_app: cmd2.Cmd) -> None:
2301 from cmd2.pt_utils import Cmd2Completer
2302
2303 mock_parser = mock.MagicMock()
2304 completer = base_app._resolve_completer(parser=mock_parser)
2305 assert isinstance(completer, Cmd2Completer)
2306
2307 # Verify contents
2308 settings = completer.custom_settings
2309 assert settings is not None
2310
2311 assert settings.parser == mock_parser
2312 assert not settings.preserve_quotes
2313
2314
2315 def test_resolve_completer_with_bad_input(base_app: cmd2.Cmd) -> None:
2316 mock_provider = mock.MagicMock()
2317 mock_completer = mock.MagicMock()
2318 mock_parser = mock.MagicMock()
2319
2320 with pytest.raises(ValueError) as excinfo: # noqa: PT011
2321 base_app._resolve_completer(
2322 choices=[],
2323 choices_provider=mock_provider,
2324 completer=mock_completer,
2325 parser=mock_parser,
2326 )
2327
2328 assert "None of the following parameters can be used alongside a parser" in str(excinfo.value)
2329
2330
2331 def test_custom_stdout() -> None:
2332 # Create a custom file-like object (e.g., an in-memory string buffer)
2333 custom_output = io.StringIO()
2334
2335 # Instantiate cmd2.Cmd with the custom_output as stdout
2336 my_app = cmd2.Cmd(stdout=custom_output)
2337
2338 # Simulate a command
2339 my_app.onecmd("help")
2340
2341 # Retrieve the output from the custom_output buffer
2342 captured_output = custom_output.getvalue()
2343 assert "history" in captured_output
2344
2345
2346 def test_read_command_line_eof(base_app, monkeypatch) -> None:
2347 """Test that _read_command_line passes up EOFErrors."""
2348 read_raw_mock = mock.MagicMock(name="_read_raw_input", side_effect=EOFError)
2349 monkeypatch.setattr("cmd2.Cmd._read_raw_input", read_raw_mock)
2350
2351 with pytest.raises(EOFError):
2352 base_app._read_command_line("Prompt> ")
2353
2354
2355 def test_read_input_eof(base_app, monkeypatch) -> None:
2356 """Test that read_input passes up EOFErrors."""
2357 read_raw_mock = mock.MagicMock(name="_read_raw_input", side_effect=EOFError)
2358 monkeypatch.setattr("cmd2.Cmd._read_raw_input", read_raw_mock)
2359
2360 with pytest.raises(EOFError):
2361 base_app.read_input("Prompt> ")
2362
2363
2364 def test_read_secret(base_app, monkeypatch):
2365 """Test read_secret passes is_password=True to _read_raw_input."""
2366 with mock.patch.object(base_app, "_read_raw_input") as mock_reader:
2367 mock_reader.return_value = "my_secret"
2368
2369 secret = base_app.read_secret("Secret: ")
2370
2371 assert secret == "my_secret"
2372 # Verify it called _read_raw_input with is_password=True
2373 args, kwargs = mock_reader.call_args
2374 assert args[0] == "Secret: "
2375 assert kwargs["is_password"] is True
2376
2377
2378 def test_read_secret_eof(base_app, monkeypatch):
2379 """Test that read_secret passes up EOFErrors."""
2380 read_raw_mock = mock.MagicMock(name="_read_raw_input", side_effect=EOFError)
2381 monkeypatch.setattr("cmd2.Cmd._read_raw_input", read_raw_mock)
2382
2383 with pytest.raises(EOFError):
2384 base_app.read_secret("Secret: ")
2385
2386
2387 def test_read_input_passes_all_arguments_to_resolver(base_app):
2388 mock_choices = ["choice1", "choice2"]
2389 mock_provider = mock.MagicMock(name="provider")
2390 mock_completer = mock.MagicMock(name="completer")
2391 mock_parser = mock.MagicMock(name="parser")
2392
2393 with (
2394 mock.patch.object(base_app, "_resolve_completer") as mock_resolver,
2395 mock.patch.object(base_app, "_read_raw_input") as mock_reader,
2396 ):
2397 mock_resolver.return_value = mock.MagicMock()
2398 mock_reader.return_value = mock.MagicMock()
2399
2400 base_app.read_input(
2401 prompt="Enter command: ",
2402 history=["prev_cmd"],
2403 preserve_quotes=True,
2404 choices=mock_choices,
2405 choices_provider=mock_provider,
2406 completer=mock_completer,
2407 parser=mock_parser,
2408 )
2409
2410 mock_resolver.assert_called_once_with(
2411 preserve_quotes=True,
2412 choices=mock_choices,
2413 choices_provider=mock_provider,
2414 completer=mock_completer,
2415 parser=mock_parser,
2416 )
2417
2418
2419 def test_read_input_history_is_passed_to_session(base_app, monkeypatch, mocker):
2420 mock_session_cls = mocker.patch("cmd2.cmd2.PromptSession")
2421 mock_history_cls = mocker.patch("cmd2.cmd2.InMemoryHistory")
2422 read_raw_mock = mocker.MagicMock(name="_read_raw_input", return_value="command")
2423 monkeypatch.setattr("cmd2.Cmd._read_raw_input", read_raw_mock)
2424
2425 # Test with custom history first
2426 my_history_list = ["help", "help alias", "help help"]
2427 base_app.read_input(history=my_history_list)
2428 mock_history_cls.assert_called_once_with(my_history_list)
2429
2430 called_kwargs = mock_session_cls.call_args.kwargs
2431 assert called_kwargs["history"] == mock_history_cls.return_value
2432
2433 # Test with no history
2434 mock_history_cls.reset_mock()
2435 mock_session_cls.reset_mock()
2436 my_history_list = ["help", "help alias", "help help"]
2437 base_app.read_input(history=None)
2438 mock_history_cls.assert_called_once_with()
2439
2440 called_kwargs = mock_session_cls.call_args.kwargs
2441 assert called_kwargs["history"] == mock_history_cls.return_value
2442
2443
2444 def test_read_raw_input_session_usage_and_restore(base_app, mocker):
2445 mock_session = mocker.MagicMock(name="temp_session")
2446 base_app.main_session = mocker.MagicMock(name="main_session")
2447
2448 # Make sure we look like a terminal
2449 mocker.patch.object(base_app, "_is_tty_session", return_value=True)
2450
2451 command_text = "help alias"
2452
2453 def check_and_return_input(*args, **kwargs):
2454 # Check if the active session was the one we passed in
2455 assert base_app.active_session == mock_session
2456 return command_text
2457
2458 mock_session.prompt.side_effect = check_and_return_input
2459
2460 # Mock patch_stdout to prevent it from attempting to access the Windows
2461 # console buffer in a Windows test environment.
2462 with mock.patch("cmd2.cmd2.patch_stdout"):
2463 result = base_app._read_raw_input("prompt> ", mock_session)
2464
2465 assert result == command_text
2466
2467 # Check if session.prompt() was called
2468 mock_session.prompt.assert_called_once()
2469
2470 # Verify that active session was restored
2471 assert base_app.active_session == base_app.main_session
2472
2473
2474 def test_read_raw_input_restores_on_error(base_app, mocker):
2475 mock_session = mocker.MagicMock()
2476 base_app.main_session = mocker.MagicMock(name="main_session")
2477
2478 # Make sure we look like a terminal
2479 mocker.patch.object(base_app, "_is_tty_session", return_value=True)
2480
2481 def check_and_raise(*args, **kwargs):
2482 # Check if the active session was the one we passed in
2483 assert base_app.active_session == mock_session
2484 raise KeyboardInterrupt
2485
2486 mock_session.prompt.side_effect = check_and_raise
2487
2488 # Mock patch_stdout to prevent it from attempting to access the Windows
2489 # console buffer in a Windows test environment.
2490 with mock.patch("cmd2.cmd2.patch_stdout"), pytest.raises(KeyboardInterrupt):
2491 base_app._read_raw_input("prompt> ", mock_session)
2492
2493 # Even though an error occurred, the finally block restored active session
2494 assert base_app.active_session == base_app.main_session
2495
2496
2497 def test_poutput_string(outsim_app) -> None:
2498 msg = "This is a test"
2499 outsim_app.poutput(msg)
2500 out = outsim_app.stdout.getvalue()
2501 expected = msg + "\n"
2502 assert out == expected
2503
2504
2505 def test_poutput_zero(outsim_app) -> None:
2506 msg = 0
2507 outsim_app.poutput(msg)
2508 out = outsim_app.stdout.getvalue()
2509 expected = str(msg) + "\n"
2510 assert out == expected
2511
2512
2513 def test_poutput_empty_string(outsim_app) -> None:
2514 msg = ""
2515 outsim_app.poutput(msg)
2516 out = outsim_app.stdout.getvalue()
2517 expected = "\n"
2518 assert out == expected
2519
2520
2521 def test_poutput_none(outsim_app) -> None:
2522 msg = None
2523 outsim_app.poutput(msg)
2524 out = outsim_app.stdout.getvalue()
2525 expected = "None\n"
2526 assert out == expected
2527
2528
2529 @with_ansi_style(ru.AllowStyle.ALWAYS)
2530 @pytest.mark.parametrize(
2531 # Test a Rich Text and a string.
2532 ("styled_msg", "expected"),
2533 [
2534 (Text("A Text object", style="cyan"), "\x1b[36mA Text object\x1b[0m\n"),
2535 (su.stylize("A str object", style="blue"), "\x1b[34mA str object\x1b[0m\n"),
2536 ],
2537 )
2538 def test_poutput_ansi_always(styled_msg, expected, outsim_app) -> None:
2539 outsim_app.poutput(styled_msg)
2540 out = outsim_app.stdout.getvalue()
2541 assert out == expected
2542
2543
2544 @with_ansi_style(ru.AllowStyle.NEVER)
2545 @pytest.mark.parametrize(
2546 # Test a Rich Text and a string.
2547 ("styled_msg", "expected"),
2548 [
2549 (Text("A Text object", style="cyan"), "A Text object\n"),
2550 (su.stylize("A str object", style="blue"), "A str object\n"),
2551 ],
2552 )
2553 def test_poutput_ansi_never(styled_msg, expected, outsim_app) -> None:
2554 outsim_app.poutput(styled_msg)
2555 out = outsim_app.stdout.getvalue()
2556 assert out == expected
2557
2558
2559 @with_ansi_style(ru.AllowStyle.TERMINAL)
2560 def test_poutput_ansi_terminal(outsim_app) -> None:
2561 """Test that AllowStyle.TERMINAL strips style when redirecting."""
2562 msg = "testing..."
2563 colored_msg = Text(msg, style="cyan")
2564 outsim_app._redirecting = True
2565 outsim_app.poutput(colored_msg)
2566 out = outsim_app.stdout.getvalue()
2567 expected = msg + "\n"
2568 assert out == expected
2569
2570
2571 @with_ansi_style(ru.AllowStyle.ALWAYS)
2572 def test_poutput_highlight(outsim_app):
2573 outsim_app.poutput("My IP Address is 192.168.1.100.", highlight=True)
2574 out = outsim_app.stdout.getvalue()
2575 assert out == "My IP Address is \x1b[1;92m192.168.1.100\x1b[0m.\n"
2576
2577
2578 @with_ansi_style(ru.AllowStyle.ALWAYS)
2579 def test_poutput_markup(outsim_app):
2580 outsim_app.poutput("The leaves are [green]green[/green].", markup=True)
2581 out = outsim_app.stdout.getvalue()
2582 assert out == "The leaves are \x1b[32mgreen\x1b[0m.\n"
2583
2584
2585 @with_ansi_style(ru.AllowStyle.ALWAYS)
2586 def test_poutput_emoji(outsim_app):
2587 outsim_app.poutput("Look at the emoji :1234:.", emoji=True)
2588 out = outsim_app.stdout.getvalue()
2589 assert out == "Look at the emoji 🔢.\n"
2590
2591
2592 @with_ansi_style(ru.AllowStyle.ALWAYS)
2593 def test_poutput_justify_and_width(outsim_app):
2594 rich_print_kwargs = {"width": 10}
2595
2596 # Use a styled-string when justifying to check if its display width is correct.
2597 outsim_app.poutput(
2598 su.stylize("Hello", style="blue"),
2599 justify="right",
2600 rich_print_kwargs=rich_print_kwargs,
2601 )
2602 out = outsim_app.stdout.getvalue()
2603 assert out == " \x1b[34mHello\x1b[0m\n"
2604
2605
2606 def test_rich_print_kwargs(outsim_app):
2607 rich_print_kwargs = {"no_wrap": True, "overflow": "ellipsis", "width": 10}
2608
2609 outsim_app.poutput(
2610 "This is longer than width.",
2611 soft_wrap=False,
2612 rich_print_kwargs=rich_print_kwargs,
2613 )
2614 out = outsim_app.stdout.getvalue()
2615 assert out.startswith("This is l…\n")
2616
2617
2618 @with_ansi_style(ru.AllowStyle.ALWAYS)
2619 def test_poutput_pretty_print(outsim_app):
2620 """Test that cmd2 passes objects through so they can be pretty-printed when highlighting is enabled."""
2621 dictionary = {1: "hello", 2: "person", 3: "who", 4: "codes"}
2622
2623 outsim_app.poutput(dictionary, highlight=True)
2624 out = outsim_app.stdout.getvalue()
2625 assert out.startswith("\x1b[1m{\x1b[0m\x1b[1;36m1\x1b[0m: \x1b[32m'hello'\x1b[0m")
2626
2627
2628 @pytest.mark.parametrize(
2629 "stream",
2630 ["stdout", "stderr"],
2631 )
2632 @pytest.mark.parametrize(
2633 ("emoji", "markup", "highlight"),
2634 [
2635 (True, True, True),
2636 (False, False, False),
2637 (True, False, True),
2638 ],
2639 )
2640 def test_get_core_print_console_caching(base_app: cmd2.Cmd, stream: str, emoji: bool, markup: bool, highlight: bool) -> None:
2641 """Test that printing consoles are cached and reused when settings match."""
2642 file = sys.stderr if stream == "stderr" else base_app.stdout
2643
2644 # Initial creation
2645 console1 = base_app._get_core_print_console(
2646 file=file,
2647 emoji=emoji,
2648 markup=markup,
2649 highlight=highlight,
2650 )
2651
2652 # Verify it's in the cache
2653 cached = getattr(base_app._console_cache, stream)
2654 assert cached is console1
2655
2656 # Identical request should return the same object
2657 console2 = base_app._get_core_print_console(
2658 file=file,
2659 emoji=emoji,
2660 markup=markup,
2661 highlight=highlight,
2662 )
2663 assert console2 is console1
2664
2665
2666 @pytest.mark.parametrize(
2667 "stream",
2668 ["stdout", "stderr"],
2669 )
2670 def test_get_core_print_console_invalidation(base_app: cmd2.Cmd, stream: str) -> None:
2671 """Test that changing settings, theme, or ALLOW_STYLE invalidates the cache."""
2672 file = sys.stderr if stream == "stderr" else base_app.stdout
2673
2674 # Initial creation
2675 console1 = base_app._get_core_print_console(
2676 file=file,
2677 emoji=True,
2678 markup=True,
2679 highlight=True,
2680 )
2681
2682 # Changing emoji should create a new console
2683 console2 = base_app._get_core_print_console(
2684 file=file,
2685 emoji=False,
2686 markup=True,
2687 highlight=True,
2688 )
2689 assert console2 is not console1
2690 assert getattr(base_app._console_cache, stream) is console2
2691
2692 # Changing markup should create a new console
2693 console3 = base_app._get_core_print_console(
2694 file=file,
2695 emoji=False,
2696 markup=False,
2697 highlight=True,
2698 )
2699 assert console3 is not console2
2700 assert getattr(base_app._console_cache, stream) is console3
2701
2702 # Changing highlight should create a new console
2703 console4 = base_app._get_core_print_console(
2704 file=file,
2705 emoji=False,
2706 markup=False,
2707 highlight=False,
2708 )
2709 assert console4 is not console3
2710 assert getattr(base_app._console_cache, stream) is console4
2711
2712 # Changing ALLOW_STYLE should create a new console
2713 orig_allow_style = ru.ALLOW_STYLE
2714 try:
2715 ru.ALLOW_STYLE = ru.AllowStyle.ALWAYS if orig_allow_style != ru.AllowStyle.ALWAYS else ru.AllowStyle.NEVER
2716 console5 = base_app._get_core_print_console(
2717 file=file,
2718 emoji=False,
2719 markup=False,
2720 highlight=False,
2721 )
2722 assert console5 is not console4
2723 assert getattr(base_app._console_cache, stream) is console5
2724 finally:
2725 ru.ALLOW_STYLE = orig_allow_style
2726
2727 # Changing the theme object should create a new console
2728 from rich.theme import Theme
2729
2730 from cmd2 import theme
2731
2732 old_theme = theme.get_theme()
2733 try:
2734 theme._THEME = Theme()
2735 console6 = base_app._get_core_print_console(
2736 file=file,
2737 emoji=False,
2738 markup=False,
2739 highlight=False,
2740 )
2741 assert console6 is not console5
2742 assert getattr(base_app._console_cache, stream) is console6
2743 finally:
2744 theme._THEME = old_theme
2745
2746
2747 def test_get_core_print_console_non_cached(base_app: cmd2.Cmd) -> None:
2748 """Test that arbitrary file objects are not cached."""
2749 file = io.StringIO()
2750
2751 console1 = base_app._get_core_print_console(
2752 file=file,
2753 emoji=True,
2754 markup=True,
2755 highlight=True,
2756 )
2757
2758 # Cache for stdout/stderr should still be None (assuming they haven't been touched yet)
2759 assert base_app._console_cache.stdout is None
2760 assert base_app._console_cache.stderr is None
2761
2762 # A second request for the same file should still create a new object
2763 console2 = base_app._get_core_print_console(
2764 file=file,
2765 emoji=True,
2766 markup=True,
2767 highlight=True,
2768 )
2769 assert console2 is not console1
2770
2771
2772 def test_broken_pipe_error(outsim_app, monkeypatch, capsys):
2773 write_mock = mock.MagicMock()
2774 write_mock.side_effect = BrokenPipeError
2775 monkeypatch.setattr("cmd2.utils.StdSim.write", write_mock)
2776
2777 outsim_app.broken_pipe_warning = "The pipe broke"
2778 outsim_app.poutput("My test string")
2779
2780 out, err = capsys.readouterr()
2781 assert not out
2782 assert outsim_app.broken_pipe_warning in err
2783
2784
2785 # These are invalid names for aliases and macros
2786 invalid_command_name = [
2787 '""', # Blank name
2788 constants.COMMENT_CHAR,
2789 "!no_shortcut",
2790 '">"',
2791 '"no>pe"',
2792 '"no spaces"',
2793 '"nopipe|"',
2794 '"noterm;"',
2795 'noembedded"quotes',
2796 ]
2797
2798
2799 def test_get_alias_choices(base_app: cmd2.Cmd) -> None:
2800 run_cmd(base_app, "alias create fake run_pyscript")
2801 run_cmd(base_app, "alias create ls !ls -hal")
2802
2803 choices = base_app._get_alias_choices()
2804
2805 aliases = base_app.aliases
2806 assert len(choices) == len(aliases)
2807
2808 for cur_choice in choices:
2809 assert cur_choice.text in aliases
2810 assert cur_choice.display_meta == aliases[cur_choice.text]
2811 assert cur_choice.table_data == (aliases[cur_choice.text],)
2812
2813
2814 def test_get_macro_choices(base_app: cmd2.Cmd) -> None:
2815 run_cmd(base_app, "macro create foo !echo foo")
2816 run_cmd(base_app, "macro create bar !echo bar")
2817
2818 choices = base_app._get_macro_choices()
2819
2820 macros = base_app.macros
2821 assert len(choices) == len(macros)
2822
2823 for cur_choice in choices:
2824 assert cur_choice.text in macros
2825 assert cur_choice.display_meta == macros[cur_choice.text].value
2826 assert cur_choice.table_data == (macros[cur_choice.text].value,)
2827
2828
2829 def test_get_commands_aliases_and_macros_choices(base_app: cmd2.Cmd) -> None:
2830 # Add an alias and a macro
2831 run_cmd(base_app, "alias create fake_alias help")
2832 run_cmd(base_app, "macro create fake_macro !echo macro")
2833
2834 # Add a command without a docstring
2835 import types
2836
2837 def do_no_doc(self, arg):
2838 pass
2839
2840 base_app.do_no_doc = types.MethodType(do_no_doc, base_app)
2841
2842 choices = base_app._get_commands_aliases_and_macros_choices()
2843
2844 # All visible commands + our new command + alias + macro
2845 expected_count = len(base_app.get_visible_commands()) + len(base_app.aliases) + len(base_app.macros)
2846 assert len(choices) == expected_count
2847
2848 # Verify alias
2849 alias_item = next((item for item in choices if item == "fake_alias"), None)
2850 assert alias_item is not None
2851 assert alias_item.display_meta == "Alias for: help"
2852
2853 # Verify macro
2854 macro_item = next((item for item in choices if item == "fake_macro"), None)
2855 assert macro_item is not None
2856 assert macro_item.display_meta == "Macro: !echo macro"
2857
2858 # Verify command with docstring (help)
2859 help_item = next((item for item in choices if item == "help"), None)
2860 assert help_item is not None
2861 # First line of help docstring
2862 assert "List available commands" in help_item.display_meta
2863
2864 # Verify command without docstring
2865 no_doc_item = next((item for item in choices if item == "no_doc"), None)
2866 assert no_doc_item is not None
2867 assert no_doc_item.display_meta == ""
2868
2869
2870 def test_get_settable_choices(base_app: cmd2.Cmd) -> None:
2871 choices = base_app._get_settable_choices()
2872 assert len(choices) == len(base_app.settables)
2873
2874 for cur_choice in choices:
2875 cur_settable = base_app.settables.get(cur_choice.text)
2876 assert cur_settable is not None
2877
2878 # Convert fields so we can compare them
2879 str_value = str(cur_settable.value)
2880
2881 choice_value = cur_choice.table_data[0]
2882 if isinstance(choice_value, Text):
2883 choice_value = ru.rich_text_to_string(choice_value)
2884
2885 choice_description = cur_choice.table_data[1]
2886 if isinstance(choice_description, Text):
2887 choice_description = ru.rich_text_to_string(choice_description)
2888
2889 assert str_value in cur_choice.display_meta
2890 assert choice_value == str_value
2891 assert choice_description == cur_settable.description
2892
2893
2894 def test_alias_no_subcommand(base_app) -> None:
2895 _out, err = run_cmd(base_app, "alias")
2896 assert "Usage: alias [-h]" in err[0]
2897 assert "Error: the following arguments are required: SUBCOMMAND" in err[1]
2898
2899
2900 def test_alias_create(base_app) -> None:
2901 # Create the alias
2902 out, err = run_cmd(base_app, "alias create fake run_pyscript")
2903 assert out == normalize("Alias 'fake' created")
2904 assert base_app.last_result is True
2905
2906 # Use the alias
2907 out, err = run_cmd(base_app, "fake")
2908 assert "the following arguments are required: script_path" in err[1]
2909
2910 # See a list of aliases
2911 out, err = run_cmd(base_app, "alias list")
2912 assert out == normalize("alias create fake run_pyscript")
2913 assert len(base_app.last_result) == len(base_app.aliases)
2914 assert base_app.last_result["fake"] == "run_pyscript"
2915
2916 # Look up the new alias
2917 out, err = run_cmd(base_app, "alias list fake")
2918 assert out == normalize("alias create fake run_pyscript")
2919 assert len(base_app.last_result) == 1
2920 assert base_app.last_result["fake"] == "run_pyscript"
2921
2922 # Overwrite alias
2923 out, err = run_cmd(base_app, "alias create fake help")
2924 assert out == normalize("Alias 'fake' overwritten")
2925 assert base_app.last_result is True
2926
2927 # Look up the updated alias
2928 out, err = run_cmd(base_app, "alias list fake")
2929 assert out == normalize("alias create fake help")
2930 assert len(base_app.last_result) == 1
2931 assert base_app.last_result["fake"] == "help"
2932
2933
2934 def test_nested_alias_usage(base_app) -> None:
2935 run_cmd(base_app, "alias create nested help")
2936 run_cmd(base_app, "alias create wrapper nested")
2937 nested_out = run_cmd(base_app, "nested")
2938 wrapper_out = run_cmd(base_app, "wrapper")
2939 help_out = run_cmd(base_app, "help")
2940
2941 assert nested_out == wrapper_out == help_out
2942
2943
2944 def test_alias_create_with_quoted_tokens(base_app) -> None:
2945 """Demonstrate that quotes in alias value will be preserved"""
2946 alias_name = "fake"
2947 alias_command = 'help ">" "out file.txt" ";"'
2948 create_command = f"alias create {alias_name} {alias_command}"
2949
2950 # Create the alias
2951 out, _err = run_cmd(base_app, create_command)
2952 assert out == normalize("Alias 'fake' created")
2953
2954 # Look up the new alias and verify all quotes are preserved
2955 out, _err = run_cmd(base_app, "alias list fake")
2956 assert out == normalize(create_command)
2957 assert len(base_app.last_result) == 1
2958 assert base_app.last_result[alias_name] == alias_command
2959
2960
2961 @pytest.mark.parametrize("alias_name", invalid_command_name)
2962 def test_alias_create_invalid_name(base_app, alias_name, capsys) -> None:
2963 _out, err = run_cmd(base_app, f"alias create {alias_name} help")
2964 assert "Invalid alias name" in err[0]
2965 assert base_app.last_result is False
2966
2967
2968 def test_alias_create_with_command_name(base_app) -> None:
2969 _out, err = run_cmd(base_app, "alias create help stuff")
2970 assert "Alias cannot have the same name as a command" in err[0]
2971 assert base_app.last_result is False
2972
2973
2974 def test_alias_create_with_macro_name(base_app) -> None:
2975 macro = "my_macro"
2976 run_cmd(base_app, f"macro create {macro} help")
2977 _out, err = run_cmd(base_app, f"alias create {macro} help")
2978 assert "Alias cannot have the same name as a macro" in err[0]
2979 assert base_app.last_result is False
2980
2981
2982 def test_alias_that_resolves_into_comment(base_app) -> None:
2983 # Create the alias
2984 out, err = run_cmd(base_app, "alias create fake " + constants.COMMENT_CHAR + " blah blah")
2985 assert out == normalize("Alias 'fake' created")
2986
2987 # Use the alias
2988 out, err = run_cmd(base_app, "fake")
2989 assert not out
2990 assert not err
2991
2992
2993 def test_alias_list_invalid_alias(base_app) -> None:
2994 # Look up invalid alias
2995 _out, err = run_cmd(base_app, "alias list invalid")
2996 assert "Alias 'invalid' not found" in err[0]
2997 assert base_app.last_result == {}
2998
2999
3000 def test_alias_delete(base_app) -> None:
3001 # Create an alias
3002 run_cmd(base_app, "alias create fake run_pyscript")
3003
3004 # Delete the alias
3005 out, _err = run_cmd(base_app, "alias delete fake")
3006 assert out == normalize("Alias 'fake' deleted")
3007 assert base_app.last_result is True
3008
3009
3010 def test_alias_delete_all(base_app) -> None:
3011 out, _err = run_cmd(base_app, "alias delete --all")
3012 assert out == normalize("All aliases deleted")
3013 assert base_app.last_result is True
3014
3015
3016 def test_alias_delete_non_existing(base_app) -> None:
3017 _out, err = run_cmd(base_app, "alias delete fake")
3018 assert "Alias 'fake' does not exist" in err[0]
3019 assert base_app.last_result is True
3020
3021
3022 def test_alias_delete_no_name(base_app) -> None:
3023 _out, err = run_cmd(base_app, "alias delete")
3024 assert "Either --all or alias name(s)" in err[0]
3025 assert base_app.last_result is False
3026
3027
3028 def test_multiple_aliases(base_app) -> None:
3029 alias1 = "h1"
3030 alias2 = "h2"
3031 run_cmd(base_app, f"alias create {alias1} help")
3032 run_cmd(base_app, f"alias create {alias2} help -v")
3033 out, _err = run_cmd(base_app, alias1)
3034 verify_help_text(base_app, out)
3035
3036 out, _err = run_cmd(base_app, alias2)
3037 verify_help_text(base_app, out)
3038
3039
3040 def test_macro_no_subcommand(base_app) -> None:
3041 _out, err = run_cmd(base_app, "macro")
3042 assert "Usage: macro [-h]" in err[0]
3043 assert "Error: the following arguments are required: SUBCOMMAND" in err[1]
3044
3045
3046 def test_macro_create(base_app) -> None:
3047 # Create the macro
3048 out, err = run_cmd(base_app, "macro create fake run_pyscript")
3049 assert out == normalize("Macro 'fake' created")
3050 assert base_app.last_result is True
3051
3052 # Use the macro
3053 out, err = run_cmd(base_app, "fake")
3054 assert "the following arguments are required: script_path" in err[1]
3055
3056 # See a list of macros
3057 out, err = run_cmd(base_app, "macro list")
3058 assert out == normalize("macro create fake run_pyscript")
3059 assert len(base_app.last_result) == len(base_app.macros)
3060 assert base_app.last_result["fake"] == "run_pyscript"
3061
3062 # Look up the new macro
3063 out, err = run_cmd(base_app, "macro list fake")
3064 assert out == normalize("macro create fake run_pyscript")
3065 assert len(base_app.last_result) == 1
3066 assert base_app.last_result["fake"] == "run_pyscript"
3067
3068 # Overwrite macro
3069 out, err = run_cmd(base_app, "macro create fake help")
3070 assert out == normalize("Macro 'fake' overwritten")
3071 assert base_app.last_result is True
3072
3073 # Look up the updated macro
3074 out, err = run_cmd(base_app, "macro list fake")
3075 assert out == normalize("macro create fake help")
3076 assert len(base_app.last_result) == 1
3077 assert base_app.last_result["fake"] == "help"
3078
3079
3080 def test_macro_create_with_quoted_tokens(base_app) -> None:
3081 """Demonstrate that quotes in macro value will be preserved"""
3082 macro_name = "fake"
3083 macro_command = 'help ">" "out file.txt" ";"'
3084 create_command = f"macro create {macro_name} {macro_command}"
3085
3086 # Create the macro
3087 out, _err = run_cmd(base_app, create_command)
3088 assert out == normalize("Macro 'fake' created")
3089
3090 # Look up the new macro and verify all quotes are preserved
3091 out, _err = run_cmd(base_app, "macro list fake")
3092 assert out == normalize(create_command)
3093 assert len(base_app.last_result) == 1
3094 assert base_app.last_result[macro_name] == macro_command
3095
3096
3097 @pytest.mark.parametrize("macro_name", invalid_command_name)
3098 def test_macro_create_invalid_name(base_app, macro_name) -> None:
3099 _out, err = run_cmd(base_app, f"macro create {macro_name} help")
3100 assert "Invalid macro name" in err[0]
3101 assert base_app.last_result is False
3102
3103
3104 def test_macro_create_with_command_name(base_app) -> None:
3105 _out, err = run_cmd(base_app, "macro create help stuff")
3106 assert "Macro cannot have the same name as a command" in err[0]
3107 assert base_app.last_result is False
3108
3109
3110 def test_macro_create_with_alias_name(base_app) -> None:
3111 macro = "my_macro"
3112 run_cmd(base_app, f"alias create {macro} help")
3113 _out, err = run_cmd(base_app, f"macro create {macro} help")
3114 assert "Macro cannot have the same name as an alias" in err[0]
3115 assert base_app.last_result is False
3116
3117
3118 def test_macro_create_with_args(base_app) -> None:
3119 # Create the macro
3120 out, _err = run_cmd(base_app, "macro create fake {1} {2}")
3121 assert out == normalize("Macro 'fake' created")
3122
3123 # Run the macro
3124 out, _err = run_cmd(base_app, "fake help -v")
3125 verify_help_text(base_app, out)
3126
3127
3128 def test_macro_create_with_escaped_args(base_app) -> None:
3129 # Create the macro
3130 out, err = run_cmd(base_app, "macro create fake help {{1}}")
3131 assert out == normalize("Macro 'fake' created")
3132
3133 # Run the macro
3134 out, err = run_cmd(base_app, "fake")
3135 assert err[0].startswith("No help on {1}")
3136
3137
3138 def test_macro_usage_with_missing_args(base_app) -> None:
3139 # Create the macro
3140 out, err = run_cmd(base_app, "macro create fake help {1} {2}")
3141 assert out == normalize("Macro 'fake' created")
3142
3143 # Run the macro
3144 out, err = run_cmd(base_app, "fake arg1")
3145 assert "expects at least 2 arguments" in err[0]
3146
3147
3148 def test_macro_usage_with_extra_args(base_app) -> None:
3149 # Create the macro
3150 out, _err = run_cmd(base_app, "macro create fake help {1}")
3151 assert out == normalize("Macro 'fake' created")
3152
3153 # Run the macro
3154 out, _err = run_cmd(base_app, "fake alias create")
3155 assert "Usage: alias create" in out[0]
3156
3157
3158 def test_nested_macro_usage(base_app) -> None:
3159 run_cmd(base_app, "macro create nested help")
3160 run_cmd(base_app, "macro create wrapper nested {1}")
3161 nested_out = run_cmd(base_app, "nested")
3162 help_out = run_cmd(base_app, "help")
3163 assert nested_out == help_out
3164
3165 wrapper_out = run_cmd(base_app, "wrapper alias")
3166 help_alias_out = run_cmd(base_app, "help alias")
3167
3168 assert wrapper_out == help_alias_out
3169
3170
3171 def test_macro_create_with_missing_arg_nums(base_app) -> None:
3172 # Create the macro
3173 _out, err = run_cmd(base_app, "macro create fake help {1} {3}")
3174 assert "Not all numbers between 1 and 3" in err[0]
3175 assert base_app.last_result is False
3176
3177
3178 def test_macro_create_with_invalid_arg_num(base_app) -> None:
3179 # Create the macro
3180 _out, err = run_cmd(base_app, "macro create fake help {1} {-1} {0}")
3181 assert "Argument numbers must be greater than 0" in err[0]
3182 assert base_app.last_result is False
3183
3184
3185 def test_macro_create_with_unicode_numbered_arg(base_app) -> None:
3186 # Create the macro expecting 1 argument
3187 out, err = run_cmd(base_app, "macro create fake help {\N{ARABIC-INDIC DIGIT ONE}}")
3188 assert out == normalize("Macro 'fake' created")
3189
3190 # Run the macro
3191 out, err = run_cmd(base_app, "fake")
3192 assert "expects at least 1 argument" in err[0]
3193
3194
3195 def test_macro_create_with_missing_unicode_arg_nums(base_app) -> None:
3196 _out, err = run_cmd(base_app, "macro create fake help {1} {\N{ARABIC-INDIC DIGIT THREE}}")
3197 assert "Not all numbers between 1 and 3" in err[0]
3198 assert base_app.last_result is False
3199
3200
3201 def test_macro_that_resolves_into_comment(base_app) -> None:
3202 # Create the macro
3203 out, err = run_cmd(base_app, "macro create fake {1} blah blah")
3204 assert out == normalize("Macro 'fake' created")
3205
3206 # Use the macro
3207 out, err = run_cmd(base_app, "fake " + constants.COMMENT_CHAR)
3208 assert not out
3209 assert not err
3210
3211
3212 def test_macro_list_invalid_macro(base_app) -> None:
3213 # Look up invalid macro
3214 _out, err = run_cmd(base_app, "macro list invalid")
3215 assert "Macro 'invalid' not found" in err[0]
3216 assert base_app.last_result == {}
3217
3218
3219 def test_macro_delete(base_app) -> None:
3220 # Create an macro
3221 run_cmd(base_app, "macro create fake run_pyscript")
3222
3223 # Delete the macro
3224 out, _err = run_cmd(base_app, "macro delete fake")
3225 assert out == normalize("Macro 'fake' deleted")
3226 assert base_app.last_result is True
3227
3228
3229 def test_macro_delete_all(base_app) -> None:
3230 out, _err = run_cmd(base_app, "macro delete --all")
3231 assert out == normalize("All macros deleted")
3232 assert base_app.last_result is True
3233
3234
3235 def test_macro_delete_non_existing(base_app) -> None:
3236 _out, err = run_cmd(base_app, "macro delete fake")
3237 assert "Macro 'fake' does not exist" in err[0]
3238 assert base_app.last_result is True
3239
3240
3241 def test_macro_delete_no_name(base_app) -> None:
3242 _out, err = run_cmd(base_app, "macro delete")
3243 assert "Either --all or macro name(s)" in err[0]
3244 assert base_app.last_result is False
3245
3246
3247 def test_multiple_macros(base_app) -> None:
3248 macro1 = "h1"
3249 macro2 = "h2"
3250 run_cmd(base_app, f"macro create {macro1} help")
3251 run_cmd(base_app, f"macro create {macro2} help -v")
3252 out, _err = run_cmd(base_app, macro1)
3253 verify_help_text(base_app, out)
3254
3255 out2, _err2 = run_cmd(base_app, macro2)
3256 verify_help_text(base_app, out2)
3257 assert len(out2) > len(out)
3258
3259
3260 def test_nonexistent_macro(base_app) -> None:
3261 from cmd2.parsing import (
3262 StatementParser,
3263 )
3264
3265 exception = None
3266
3267 try:
3268 base_app._resolve_macro(StatementParser().parse("fake"))
3269 except KeyError as e:
3270 exception = e
3271
3272 assert exception is not None
3273
3274
3275 @pytest.mark.parametrize(
3276 # The line of text and whether to continue prompting to finish a multiline command.
3277 ("line", "should_continue"),
3278 [
3279 # Empty lines
3280 ("", False),
3281 (" ", False),
3282 # Single-line commands
3283 ("help", False),
3284 ("help alias", False),
3285 # Multi-line commands
3286 ("orate", True),
3287 ("orate;", False),
3288 ("orate\n", False),
3289 ("orate\narg", True),
3290 ("orate\narg;", False),
3291 ("orate\narg\n", False),
3292 # Single-line macros
3293 ("single_mac", False), # macro resolution error returns False (no arg passed)
3294 ("single_mac arg", False),
3295 # Multi-line macros
3296 ("multi_mac", False), # macro resolution error returns False (no arg passed)
3297 ("multi_mac arg", True),
3298 ("multi_mac arg;", False),
3299 ("multi_mac arg\n", False),
3300 ("multi_mac\narg", True),
3301 ("multi_mac\narg;", False),
3302 ("multi_mac\narg\n", False),
3303 # Nested multi-line macros
3304 ("wrapper_mac", False), # macro resolution error returns False (no args passed)
3305 ("wrapper_mac arg", False), # macro resolution error returns False (not enough args passed)
3306 ("wrapper_mac arg arg2", True),
3307 ("wrapper_mac arg\narg2;", False),
3308 ],
3309 )
3310 def test_should_continue_multiline(multiline_app: MultilineApp, line: str, should_continue: bool) -> None:
3311 mock_buffer = mock.MagicMock()
3312 mock_buffer.text = line
3313
3314 mock_app = mock.MagicMock()
3315 mock_app.current_buffer = mock_buffer
3316
3317 run_cmd(multiline_app, "macro create single_mac help {1}")
3318 run_cmd(multiline_app, "macro create multi_mac orate {1}")
3319 run_cmd(multiline_app, "macro create wrapper_mac multi_mac {1} {2}")
3320
3321 with mock.patch("cmd2.cmd2.get_app", return_value=mock_app):
3322 assert multiline_app._should_continue_multiline() is should_continue
3323
3324
3325 @with_ansi_style(ru.AllowStyle.ALWAYS)
3326 def test_perror_style(base_app, capsys) -> None:
3327 msg = "testing..."
3328 base_app.perror(msg)
3329 _out, err = capsys.readouterr()
3330 assert err == "\x1b[91mtesting...\x1b[0m\n"
3331
3332
3333 @with_ansi_style(ru.AllowStyle.ALWAYS)
3334 def test_perror_no_style(base_app, capsys) -> None:
3335 msg = "testing..."
3336 end = "\n"
3337 base_app.perror(msg, style=None)
3338 _out, err = capsys.readouterr()
3339 assert err == msg + end
3340
3341
3342 @with_ansi_style(ru.AllowStyle.ALWAYS)
3343 def test_psuccess(outsim_app) -> None:
3344 msg = "testing..."
3345 end = "\n"
3346 outsim_app.psuccess(msg)
3347
3348 expected = su.stylize(msg + end, style=Cmd2Style.SUCCESS)
3349 assert outsim_app.stdout.getvalue() == expected
3350
3351
3352 @with_ansi_style(ru.AllowStyle.ALWAYS)
3353 def test_pwarning(base_app, capsys) -> None:
3354 msg = "testing..."
3355 end = "\n"
3356 base_app.pwarning(msg)
3357
3358 expected = su.stylize(msg + end, style=Cmd2Style.WARNING)
3359 _out, err = capsys.readouterr()
3360 assert err == expected
3361
3362
3363 @with_ansi_style(ru.AllowStyle.ALWAYS)
3364 def test_pexcept_style(base_app, capsys) -> None:
3365 msg = Exception("testing...")
3366
3367 base_app.pexcept(msg)
3368 _out, err = capsys.readouterr()
3369 expected = su.stylize("Exception: ", style="traceback.exc_type")
3370 assert err.startswith(expected)
3371
3372
3373 @with_ansi_style(ru.AllowStyle.NEVER)
3374 def test_pexcept_no_style(base_app, capsys) -> None:
3375 msg = Exception("testing...")
3376
3377 base_app.pexcept(msg)
3378 _out, err = capsys.readouterr()
3379 assert err.startswith("Exception: testing...")
3380
3381
3382 @pytest.mark.parametrize("chop", [True, False])
3383 def test_ppaged_with_pager(outsim_app, monkeypatch, chop) -> None:
3384 """Force ppaged() to run the pager by mocking an actual terminal state."""
3385
3386 # Make it look like we're in a terminal
3387 stdin_mock = mock.MagicMock()
3388 stdin_mock.isatty.return_value = True
3389 monkeypatch.setattr(outsim_app, "stdin", stdin_mock)
3390
3391 stdout_mock = mock.MagicMock()
3392 stdout_mock.isatty.return_value = True
3393 monkeypatch.setattr(outsim_app, "stdout", stdout_mock)
3394
3395 if not sys.platform.startswith("win") and os.environ.get("TERM") is None:
3396 monkeypatch.setenv("TERM", "simulated")
3397
3398 # This will force ppaged to call Popen to run a pager
3399 popen_mock = mock.MagicMock(name="Popen")
3400 monkeypatch.setattr("subprocess.Popen", popen_mock)
3401 outsim_app.ppaged("Test", chop=chop)
3402
3403 # Verify the correct pager was run
3404 expected_cmd = outsim_app.pager_chop if chop else outsim_app.pager
3405 assert len(popen_mock.call_args_list) == 1
3406 assert expected_cmd == popen_mock.call_args_list[0].args[0]
3407
3408
3409 def test_ppaged_no_pager(outsim_app) -> None:
3410 """Since we're not in a fully-functional terminal, ppaged() will just call poutput()."""
3411 msg = "testing..."
3412 end = "\n"
3413 outsim_app.ppaged(msg)
3414 out = outsim_app.stdout.getvalue()
3415 assert out == msg + end
3416
3417
3418 @pytest.mark.skipif(sys.platform.startswith("win"), reason="termios is not available on Windows")
3419 @pytest.mark.parametrize("has_tcsetpgrp", [True, False])
3420 def test_ppaged_terminal_restoration(outsim_app, monkeypatch, has_tcsetpgrp) -> None:
3421 """Test terminal restoration in ppaged() after pager exits."""
3422 # Make it look like we're in a terminal
3423 stdin_mock = mock.MagicMock()
3424 stdin_mock.isatty.return_value = True
3425 stdin_mock.fileno.return_value = 0
3426 monkeypatch.setattr(outsim_app, "stdin", stdin_mock)
3427
3428 stdout_mock = mock.MagicMock()
3429 stdout_mock.isatty.return_value = True
3430 monkeypatch.setattr(outsim_app, "stdout", stdout_mock)
3431
3432 if not sys.platform.startswith("win") and os.environ.get("TERM") is None:
3433 monkeypatch.setenv("TERM", "simulated")
3434
3435 # Mock termios and signal since they are imported within the method
3436 termios_mock = mock.MagicMock()
3437 # The error attribute needs to be the actual exception for isinstance checks
3438 import termios
3439
3440 termios_mock.error = termios.error
3441 monkeypatch.setitem(sys.modules, "termios", termios_mock)
3442
3443 signal_mock = mock.MagicMock()
3444 monkeypatch.setitem(sys.modules, "signal", signal_mock)
3445
3446 # Mock os.tcsetpgrp and os.getpgrp
3447 if has_tcsetpgrp:
3448 monkeypatch.setattr(os, "tcsetpgrp", mock.Mock(), raising=False)
3449 monkeypatch.setattr(os, "getpgrp", mock.Mock(return_value=123), raising=False)
3450 else:
3451 monkeypatch.delattr(os, "tcsetpgrp", raising=False)
3452
3453 # Mock subprocess.Popen
3454 popen_mock = mock.MagicMock(name="Popen")
3455 monkeypatch.setattr("subprocess.Popen", popen_mock)
3456
3457 # Set initial termios settings so the logic will run
3458 dummy_settings = ["dummy settings"]
3459 outsim_app._initial_termios_settings = dummy_settings
3460
3461 # Call ppaged
3462 outsim_app.ppaged("Test")
3463
3464 # Verify restoration logic
3465 if has_tcsetpgrp:
3466 os.tcsetpgrp.assert_called_once_with(0, 123)
3467 signal_mock.signal.assert_any_call(signal_mock.SIGTTOU, signal_mock.SIG_IGN)
3468
3469 termios_mock.tcsetattr.assert_called_once_with(0, termios_mock.TCSANOW, dummy_settings)
3470
3471
3472 @pytest.mark.skipif(sys.platform.startswith("win"), reason="termios is not available on Windows")
3473 def test_ppaged_terminal_restoration_exceptions(outsim_app, monkeypatch) -> None:
3474 """Test that terminal restoration in ppaged() handles exceptions gracefully."""
3475 # Make it look like we're in a terminal
3476 stdin_mock = mock.MagicMock()
3477 stdin_mock.isatty.return_value = True
3478 stdin_mock.fileno.return_value = 0
3479 monkeypatch.setattr(outsim_app, "stdin", stdin_mock)
3480
3481 stdout_mock = mock.MagicMock()
3482 stdout_mock.isatty.return_value = True
3483 monkeypatch.setattr(outsim_app, "stdout", stdout_mock)
3484
3485 if not sys.platform.startswith("win") and os.environ.get("TERM") is None:
3486 monkeypatch.setenv("TERM", "simulated")
3487
3488 # Mock termios and make it raise an error
3489 termios_mock = mock.MagicMock()
3490 import termios
3491
3492 termios_mock.error = termios.error
3493 termios_mock.tcsetattr.side_effect = termios.error("Restoration failed")
3494 monkeypatch.setitem(sys.modules, "termios", termios_mock)
3495
3496 monkeypatch.setitem(sys.modules, "signal", mock.MagicMock())
3497
3498 # Mock os.tcsetpgrp and os.getpgrp to prevent OSError before tcsetattr
3499 monkeypatch.setattr(os, "tcsetpgrp", mock.Mock(), raising=False)
3500 monkeypatch.setattr(os, "getpgrp", mock.Mock(return_value=123), raising=False)
3501
3502 # Mock subprocess.Popen
3503 popen_mock = mock.MagicMock(name="Popen")
3504 monkeypatch.setattr("subprocess.Popen", popen_mock)
3505
3506 # Set initial termios settings
3507 outsim_app._initial_termios_settings = ["dummy settings"]
3508
3509 # Call ppaged - should not raise exception
3510 outsim_app.ppaged("Test")
3511
3512 # Verify tcsetattr was attempted
3513 assert termios_mock.tcsetattr.called
3514
3515
3516 @pytest.mark.skipif(sys.platform.startswith("win"), reason="termios is not available on Windows")
3517 def test_ppaged_terminal_restoration_no_settings(outsim_app, monkeypatch) -> None:
3518 """Test that terminal restoration in ppaged() is skipped if no settings are saved."""
3519 # Make it look like we're in a terminal
3520 stdin_mock = mock.MagicMock()
3521 stdin_mock.isatty.return_value = True
3522 stdin_mock.fileno.return_value = 0
3523 monkeypatch.setattr(outsim_app, "stdin", stdin_mock)
3524
3525 stdout_mock = mock.MagicMock()
3526 stdout_mock.isatty.return_value = True
3527 monkeypatch.setattr(outsim_app, "stdout", stdout_mock)
3528
3529 if not sys.platform.startswith("win") and os.environ.get("TERM") is None:
3530 monkeypatch.setenv("TERM", "simulated")
3531
3532 # Mock termios
3533 termios_mock = mock.MagicMock()
3534 monkeypatch.setitem(sys.modules, "termios", termios_mock)
3535
3536 # Mock subprocess.Popen
3537 popen_mock = mock.MagicMock(name="Popen")
3538 monkeypatch.setattr("subprocess.Popen", popen_mock)
3539
3540 # Ensure initial termios settings is None
3541 outsim_app._initial_termios_settings = None
3542
3543 # Call ppaged
3544 outsim_app.ppaged("Test")
3545
3546 # Verify tcsetattr was NOT called
3547 assert not termios_mock.tcsetattr.called
3548
3549
3550 @pytest.mark.skipif(sys.platform.startswith("win"), reason="termios is not available on Windows")
3551 def test_ppaged_terminal_restoration_oserror(outsim_app, monkeypatch) -> None:
3552 """Test that terminal restoration in ppaged() handles OSError gracefully."""
3553 # Make it look like we're in a terminal
3554 stdin_mock = mock.MagicMock()
3555 stdin_mock.isatty.return_value = True
3556 stdin_mock.fileno.return_value = 0
3557 monkeypatch.setattr(outsim_app, "stdin", stdin_mock)
3558
3559 stdout_mock = mock.MagicMock()
3560 stdout_mock.isatty.return_value = True
3561 monkeypatch.setattr(outsim_app, "stdout", stdout_mock)
3562
3563 if not sys.platform.startswith("win") and os.environ.get("TERM") is None:
3564 monkeypatch.setenv("TERM", "simulated")
3565
3566 # Mock signal
3567 monkeypatch.setitem(sys.modules, "signal", mock.MagicMock())
3568
3569 # Mock os.tcsetpgrp to raise OSError
3570 monkeypatch.setattr(os, "tcsetpgrp", mock.Mock(side_effect=OSError("Permission denied")), raising=False)
3571 monkeypatch.setattr(os, "getpgrp", mock.Mock(return_value=123), raising=False)
3572
3573 # Mock termios
3574 termios_mock = mock.MagicMock()
3575 import termios
3576
3577 termios_mock.error = termios.error
3578 monkeypatch.setitem(sys.modules, "termios", termios_mock)
3579
3580 # Mock subprocess.Popen
3581 popen_mock = mock.MagicMock(name="Popen")
3582 monkeypatch.setattr("subprocess.Popen", popen_mock)
3583
3584 # Set initial termios settings
3585 outsim_app._initial_termios_settings = ["dummy settings"]
3586
3587 # Call ppaged - should not raise exception
3588 outsim_app.ppaged("Test")
3589
3590 # Verify tcsetpgrp was attempted and OSError was caught
3591 assert os.tcsetpgrp.called
3592 # tcsetattr should have been skipped due to OSError being raised before it
3593 assert not termios_mock.tcsetattr.called
3594
3595
3596 def test_ppretty(base_app: cmd2.Cmd) -> None:
3597 # Mock the Pretty class and the print_to() method
3598 with mock.patch("cmd2.cmd2.Pretty") as mock_pretty, mock.patch.object(cmd2.Cmd, "print_to") as mock_print_to:
3599 # Set up the mock return value for Pretty
3600 mock_pretty_obj = mock.Mock()
3601 mock_pretty.return_value = mock_pretty_obj
3602
3603 test_obj = {"key": "value"}
3604
3605 # Call ppretty() with some custom arguments
3606 base_app.ppretty(
3607 test_obj,
3608 indent_size=2,
3609 max_depth=5,
3610 expand_all=True,
3611 end="\n\n",
3612 )
3613
3614 # Verify Pretty was instantiated with the correct arguments
3615 mock_pretty.assert_called_once_with(
3616 test_obj,
3617 indent_size=2,
3618 indent_guides=True,
3619 max_length=None,
3620 max_string=None,
3621 max_depth=5,
3622 expand_all=True,
3623 overflow="ignore",
3624 )
3625
3626 # Verify print_to() was called with the mock pretty object and soft_wrap=True
3627 # It should default to self.stdout when no file is provided
3628 mock_print_to.assert_called_once_with(
3629 base_app.stdout,
3630 mock_pretty_obj,
3631 soft_wrap=True,
3632 end="\n\n",
3633 )
3634
3635
3636 def test_onecmd_raw_str_continue(outsim_app) -> None:
3637 line = "help"
3638 stop = outsim_app.onecmd(line)
3639 out = outsim_app.stdout.getvalue()
3640 assert not stop
3641 verify_help_text(outsim_app, out)
3642
3643
3644 def test_onecmd_raw_str_quit(outsim_app) -> None:
3645 line = "quit"
3646 stop = outsim_app.onecmd(line)
3647 out = outsim_app.stdout.getvalue()
3648 assert stop
3649 assert out == ""
3650
3651
3652 def test_onecmd_add_to_history(outsim_app) -> None:
3653 line = "help"
3654 saved_hist_len = len(outsim_app.history)
3655
3656 # Allow command to be added to history
3657 outsim_app.onecmd(line, add_to_history=True)
3658 new_hist_len = len(outsim_app.history)
3659 assert new_hist_len == saved_hist_len + 1
3660
3661 saved_hist_len = new_hist_len
3662
3663 # Prevent command from being added to history
3664 outsim_app.onecmd(line, add_to_history=False)
3665 new_hist_len = len(outsim_app.history)
3666 assert new_hist_len == saved_hist_len
3667
3668
3669 def test_get_all_commands(base_app) -> None:
3670 # Verify that the base app has the expected commands
3671 commands = base_app.get_all_commands()
3672 expected_commands = [
3673 "_eof",
3674 "_relative_run_script",
3675 "alias",
3676 "edit",
3677 "help",
3678 "history",
3679 "ipy",
3680 "macro",
3681 "py",
3682 "quit",
3683 "run_pyscript",
3684 "run_script",
3685 "set",
3686 "shell",
3687 "shortcuts",
3688 ]
3689 assert commands == expected_commands
3690
3691
3692 def test_get_help_topics(base_app) -> None:
3693 # Verify that the base app has no additional help_foo methods
3694 custom_help = base_app.get_help_topics()
3695 assert len(custom_help) == 0
3696
3697
3698 def test_get_help_topics_hidden() -> None:
3699 # Verify get_help_topics() filters out hidden commands
3700 class TestApp(cmd2.Cmd):
3701 def __init__(self, *args, **kwargs) -> None:
3702 super().__init__(*args, **kwargs)
3703
3704 def do_my_cmd(self, args) -> None:
3705 pass
3706
3707 def help_my_cmd(self, args) -> None:
3708 pass
3709
3710 app = TestApp()
3711 assert "my_cmd" in app.get_help_topics()
3712
3713 app.hidden_commands.append("my_cmd")
3714 assert "my_cmd" not in app.get_help_topics()
3715
3716
3717 class ReplWithExitCode(cmd2.Cmd):
3718 """Example cmd2 application where we can specify an exit code when existing."""
3719
3720 def __init__(self) -> None:
3721 super().__init__(allow_cli_args=False)
3722
3723 @cmd2.with_argument_list
3724 def do_exit(self, arg_list) -> bool:
3725 """Exit the application with an optional exit code.
3726
3727 Usage: exit [exit_code]
3728 Where:
3729 * exit_code - integer exit code to return to the shell
3730 """
3731 # If an argument was provided
3732 if arg_list:
3733 try:
3734 self.exit_code = int(arg_list[0])
3735 except ValueError:
3736 self.perror(f"{arg_list[0]} isn't a valid integer exit code")
3737 self.exit_code = 1
3738
3739 # Return True to stop the command loop
3740 return True
3741
3742 def postloop(self) -> None:
3743 """Hook method executed once when the cmdloop() method is about to return."""
3744 self.poutput(f"exiting with code: {self.exit_code}")
3745
3746
3747 @pytest.fixture
3748 def exit_code_repl():
3749 app = ReplWithExitCode()
3750 app.stdout = utils.StdSim(app.stdout)
3751 return app
3752
3753
3754 def test_exit_code_default(exit_code_repl, monkeypatch) -> None:
3755 app = exit_code_repl
3756
3757 read_command_mock = mock.MagicMock(name="_read_command_line", return_value="exit")
3758 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
3759
3760 expected = "exiting with code: 0\n"
3761
3762 # Run the command loop
3763 app.cmdloop()
3764 out = app.stdout.getvalue()
3765 assert out == expected
3766
3767
3768 def test_exit_code_nonzero(exit_code_repl, monkeypatch) -> None:
3769 app = exit_code_repl
3770
3771 read_input_mock = mock.MagicMock(name="_read_command_line", return_value="exit 23")
3772 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_input_mock)
3773
3774 expected = "exiting with code: 23\n"
3775
3776 # Run the command loop
3777 app.cmdloop()
3778 out = app.stdout.getvalue()
3779 assert out == expected
3780
3781
3782 class AnsiApp(cmd2.Cmd):
3783 def __init__(self, *args, **kwargs) -> None:
3784 super().__init__(*args, **kwargs)
3785
3786 def do_echo(self, args) -> None:
3787 self.poutput(args)
3788 self.perror(args)
3789
3790 def do_echo_error(self, args) -> None:
3791 self.poutput(args, style=Cmd2Style.ERROR)
3792 self.perror(args)
3793
3794
3795 @with_ansi_style(ru.AllowStyle.ALWAYS)
3796 def test_ansi_pouterr_always_tty(mocker, capsys) -> None:
3797 app = AnsiApp()
3798 mocker.patch.object(app.stdout, "isatty", return_value=True)
3799 mocker.patch.object(sys.stderr, "isatty", return_value=True)
3800
3801 expected_plain = "oopsie\n"
3802 expected_styled = su.stylize("oopsie\n", Cmd2Style.ERROR)
3803
3804 app.onecmd_plus_hooks("echo_error oopsie")
3805 out, err = capsys.readouterr()
3806 assert out == expected_styled
3807 assert err == expected_styled
3808
3809 app.onecmd_plus_hooks("echo oopsie")
3810 out, err = capsys.readouterr()
3811 assert out == expected_plain
3812 assert err == expected_styled
3813
3814
3815 @with_ansi_style(ru.AllowStyle.ALWAYS)
3816 def test_ansi_pouterr_always_notty(mocker, capsys) -> None:
3817 app = AnsiApp()
3818 mocker.patch.object(app.stdout, "isatty", return_value=False)
3819 mocker.patch.object(sys.stderr, "isatty", return_value=False)
3820
3821 expected_plain = "oopsie\n"
3822 expected_styled = su.stylize("oopsie\n", Cmd2Style.ERROR)
3823
3824 app.onecmd_plus_hooks("echo_error oopsie")
3825 out, err = capsys.readouterr()
3826 assert out == expected_styled
3827 assert err == expected_styled
3828
3829 app.onecmd_plus_hooks("echo oopsie")
3830 out, err = capsys.readouterr()
3831 assert out == expected_plain
3832 assert err == expected_styled
3833
3834
3835 @with_ansi_style(ru.AllowStyle.TERMINAL)
3836 def test_ansi_terminal_tty(mocker, capsys) -> None:
3837 app = AnsiApp()
3838 mocker.patch.object(app.stdout, "isatty", return_value=True)
3839 mocker.patch.object(sys.stderr, "isatty", return_value=True)
3840
3841 expected_plain = "oopsie\n"
3842 expected_styled = su.stylize("oopsie\n", Cmd2Style.ERROR)
3843
3844 app.onecmd_plus_hooks("echo_error oopsie")
3845 out, err = capsys.readouterr()
3846 assert out == expected_styled
3847 assert err == expected_styled
3848
3849 app.onecmd_plus_hooks("echo oopsie")
3850 out, err = capsys.readouterr()
3851 assert out == expected_plain
3852 assert err == expected_styled
3853
3854
3855 @with_ansi_style(ru.AllowStyle.TERMINAL)
3856 def test_ansi_terminal_notty(mocker, capsys) -> None:
3857 app = AnsiApp()
3858 mocker.patch.object(app.stdout, "isatty", return_value=False)
3859 mocker.patch.object(sys.stderr, "isatty", return_value=False)
3860
3861 app.onecmd_plus_hooks("echo_error oopsie")
3862 out, err = capsys.readouterr()
3863 assert out == err == "oopsie\n"
3864
3865 app.onecmd_plus_hooks("echo oopsie")
3866 out, err = capsys.readouterr()
3867 assert out == err == "oopsie\n"
3868
3869
3870 @with_ansi_style(ru.AllowStyle.NEVER)
3871 def test_ansi_never_tty(mocker, capsys) -> None:
3872 app = AnsiApp()
3873 mocker.patch.object(app.stdout, "isatty", return_value=True)
3874 mocker.patch.object(sys.stderr, "isatty", return_value=True)
3875
3876 app.onecmd_plus_hooks("echo_error oopsie")
3877 out, err = capsys.readouterr()
3878 assert out == err == "oopsie\n"
3879
3880 app.onecmd_plus_hooks("echo oopsie")
3881 out, err = capsys.readouterr()
3882 assert out == err == "oopsie\n"
3883
3884
3885 @with_ansi_style(ru.AllowStyle.NEVER)
3886 def test_ansi_never_notty(mocker, capsys) -> None:
3887 app = AnsiApp()
3888 mocker.patch.object(app.stdout, "isatty", return_value=False)
3889 mocker.patch.object(sys.stderr, "isatty", return_value=False)
3890
3891 app.onecmd_plus_hooks("echo_error oopsie")
3892 out, err = capsys.readouterr()
3893 assert out == err == "oopsie\n"
3894
3895 app.onecmd_plus_hooks("echo oopsie")
3896 out, err = capsys.readouterr()
3897 assert out == err == "oopsie\n"
3898
3899
3900 class DisableCommandsApp(cmd2.Cmd):
3901 """Class for disabling commands"""
3902
3903 DEFAULT_CATEGORY = "DisabledApp Commands"
3904 category_name = "Test Category"
3905
3906 def __init__(self, *args, **kwargs) -> None:
3907 super().__init__(*args, **kwargs)
3908
3909 @cmd2.with_category(category_name)
3910 def do_has_helper_func(self, arg) -> None:
3911 self.poutput("The real has_helper_func")
3912
3913 def help_has_helper_func(self) -> None:
3914 self.poutput("Help for has_helper_func")
3915
3916 def complete_has_helper_func(self, *args) -> Completions:
3917 return Completions.from_values(["result"])
3918
3919 @cmd2.with_category(category_name)
3920 def do_has_no_helper_func(self, arg) -> None:
3921 """Help for has_no_helper_func"""
3922 self.poutput("The real has_no_helper_func")
3923
3924 def do_is_not_decorated(self, arg) -> None:
3925 """This will be in the DEFAULT_CATEGORY."""
3926 self.poutput("The real is_not_decorated")
3927
3928 @cmd2.with_argparser(cmd2.Cmd2ArgumentParser())
3929 def do_argparse_command(self, args) -> None:
3930 """Help for argparse_command"""
3931
3932
3933 class DisableCommandSet(CommandSet[cmd2.Cmd]):
3934 """Test registering a command which is in a disabled category"""
3935
3936 category_name = "CommandSet Test Category"
3937 DEFAULT_CATEGORY = "DisableCommandSet Commands"
3938
3939 @cmd2.with_category(category_name)
3940 def do_new_command(self, arg) -> None:
3941 self._cmd.poutput("The real new_command")
3942
3943 def do_cs_is_not_decorated(self, arg) -> None:
3944 """This will be in the DEFAULT_CATEGORY."""
3945 self._cmd.poutput("The real cs_is_not_decorated")
3946
3947
3948 @pytest.fixture
3949 def disable_commands_app() -> DisableCommandsApp:
3950 return DisableCommandsApp()
3951
3952
3953 def test_disable_and_enable_category(disable_commands_app: DisableCommandsApp) -> None:
3954 ##########################################################################
3955 # Disable the category
3956 ##########################################################################
3957 message_to_print = "These commands are currently disabled"
3958
3959 # Disable commands which are decorated with a category
3960 disable_commands_app.disable_category(disable_commands_app.category_name, message_to_print)
3961
3962 # Disable commands in the default category
3963 disable_commands_app.disable_category(disable_commands_app.DEFAULT_CATEGORY, message_to_print)
3964
3965 # Make sure all the commands and help on those commands displays the message
3966 out, err = run_cmd(disable_commands_app, "has_helper_func")
3967 assert err[0].startswith(message_to_print)
3968
3969 out, err = run_cmd(disable_commands_app, "help has_helper_func")
3970 assert err[0].startswith(message_to_print)
3971
3972 out, err = run_cmd(disable_commands_app, "has_no_helper_func")
3973 assert err[0].startswith(message_to_print)
3974
3975 out, err = run_cmd(disable_commands_app, "help has_no_helper_func")
3976 assert err[0].startswith(message_to_print)
3977
3978 out, err = run_cmd(disable_commands_app, "is_not_decorated")
3979 assert err[0].startswith(message_to_print)
3980
3981 out, err = run_cmd(disable_commands_app, "help is_not_decorated")
3982 assert err[0].startswith(message_to_print)
3983
3984 # Make sure neither function completes
3985 text = ""
3986 line = f"has_helper_func {text}"
3987 endidx = len(line)
3988 begidx = endidx - len(text)
3989
3990 completions = disable_commands_app.complete(text, line, begidx, endidx)
3991 assert not completions
3992
3993 text = ""
3994 line = f"has_no_helper_func {text}"
3995 endidx = len(line)
3996 begidx = endidx - len(text)
3997
3998 completions = disable_commands_app.complete(text, line, begidx, endidx)
3999 assert not completions
4000
4001 # Make sure both commands are invisible
4002 visible_commands = disable_commands_app.get_visible_commands()
4003 assert "has_helper_func" not in visible_commands
4004 assert "has_no_helper_func" not in visible_commands
4005
4006 # Make sure get_help_topics() filters out disabled commands
4007 help_topics = disable_commands_app.get_help_topics()
4008 assert "has_helper_func" not in help_topics
4009
4010 ##########################################################################
4011 # Enable the category
4012 ##########################################################################
4013 # Enable commands which are decorated with a category
4014 disable_commands_app.enable_category(disable_commands_app.category_name)
4015
4016 # Enable commands in the default category
4017 disable_commands_app.enable_category(disable_commands_app.DEFAULT_CATEGORY)
4018
4019 # Make sure all the commands and help on those commands are restored
4020 out, err = run_cmd(disable_commands_app, "has_helper_func")
4021 assert out[0] == "The real has_helper_func"
4022
4023 out, err = run_cmd(disable_commands_app, "help has_helper_func")
4024 assert out[0] == "Help for has_helper_func"
4025
4026 out, err = run_cmd(disable_commands_app, "has_no_helper_func")
4027 assert out[0] == "The real has_no_helper_func"
4028
4029 out, err = run_cmd(disable_commands_app, "help has_no_helper_func")
4030 assert out[0] == "Help for has_no_helper_func"
4031
4032 out, err = run_cmd(disable_commands_app, "is_not_decorated")
4033 assert out[0] == "The real is_not_decorated"
4034
4035 # has_helper_func should complete now
4036 text = ""
4037 line = f"has_helper_func {text}"
4038 endidx = len(line)
4039 begidx = endidx - len(text)
4040
4041 completions = disable_commands_app.complete(text, line, begidx, endidx)
4042 assert completions[0].text == "result"
4043
4044 # has_no_helper_func had no completer originally, so there should be no results
4045 text = ""
4046 line = f"has_no_helper_func {text}"
4047 endidx = len(line)
4048 begidx = endidx - len(text)
4049
4050 completions = disable_commands_app.complete(text, line, begidx, endidx)
4051 assert not completions
4052
4053 # Make sure all commands are visible
4054 visible_commands = disable_commands_app.get_visible_commands()
4055 assert "has_helper_func" in visible_commands
4056 assert "has_no_helper_func" in visible_commands
4057 assert "is_not_decorated" in visible_commands
4058
4059 # Make sure get_help_topics() contains our help function
4060 help_topics = disable_commands_app.get_help_topics()
4061 assert "has_helper_func" in help_topics
4062
4063
4064 def test_enable_enabled_command(disable_commands_app) -> None:
4065 # Test enabling a command that is not disabled
4066 saved_len = len(disable_commands_app.disabled_commands)
4067 disable_commands_app.enable_command("has_helper_func")
4068
4069 # The number of disabled commands should not have changed
4070 assert saved_len == len(disable_commands_app.disabled_commands)
4071
4072
4073 def test_disable_fake_command(disable_commands_app) -> None:
4074 with pytest.raises(AttributeError):
4075 disable_commands_app.disable_command("fake", "fake message")
4076
4077
4078 def test_disable_command_twice(disable_commands_app) -> None:
4079 saved_len = len(disable_commands_app.disabled_commands)
4080 message_to_print = "These commands are currently disabled"
4081 disable_commands_app.disable_command("has_helper_func", message_to_print)
4082
4083 # The number of disabled commands should have increased one
4084 new_len = len(disable_commands_app.disabled_commands)
4085 assert saved_len == new_len - 1
4086 saved_len = new_len
4087
4088 # Disable again and the length should not change
4089 disable_commands_app.disable_command("has_helper_func", message_to_print)
4090 new_len = len(disable_commands_app.disabled_commands)
4091 assert saved_len == new_len
4092
4093
4094 def test_disabled_command_not_in_history(disable_commands_app) -> None:
4095 message_to_print = "These commands are currently disabled"
4096 disable_commands_app.disable_command("has_helper_func", message_to_print)
4097
4098 saved_len = len(disable_commands_app.history)
4099 run_cmd(disable_commands_app, "has_helper_func")
4100 assert saved_len == len(disable_commands_app.history)
4101
4102
4103 def test_get_parser_while_disabled(disable_commands_app: DisableCommandsApp) -> None:
4104 """Test that command_parsers can find a disabled command's parser."""
4105 # Get parser before disabling
4106 parser_before = disable_commands_app.command_parsers.get(disable_commands_app.do_argparse_command)
4107 assert parser_before is not None
4108
4109 # Disable command
4110 disable_commands_app.disable_command("argparse_command", "Disabled")
4111
4112 # Get parser after disabling
4113 parser_after = disable_commands_app.command_parsers.get(disable_commands_app.do_argparse_command)
4114 assert parser_after is not None
4115 assert parser_after is parser_before
4116
4117
4118 def test_metadata_preservation_while_disabled(disable_commands_app: DisableCommandsApp) -> None:
4119 orig_cmd_func = disable_commands_app.do_has_helper_func
4120 orig_help = disable_commands_app.help_has_helper_func
4121 orig_complete = disable_commands_app.complete_has_helper_func
4122
4123 disable_commands_app.disable_command("has_helper_func", "Disabled")
4124
4125 # Names and qualnames should be preserved
4126 assert disable_commands_app.do_has_helper_func.__name__ == orig_cmd_func.__name__
4127 assert disable_commands_app.do_has_helper_func.__qualname__ == orig_cmd_func.__qualname__
4128
4129 assert disable_commands_app.help_has_helper_func.__name__ == orig_help.__name__
4130 assert disable_commands_app.help_has_helper_func.__qualname__ == orig_help.__qualname__
4131
4132 assert disable_commands_app.complete_has_helper_func.__name__ == orig_complete.__name__
4133 assert disable_commands_app.complete_has_helper_func.__qualname__ == orig_complete.__qualname__
4134
4135 # Docstrings should be preserved
4136 assert disable_commands_app.do_has_helper_func.__doc__ == orig_cmd_func.__doc__
4137 assert disable_commands_app.help_has_helper_func.__doc__ == orig_help.__doc__
4138 assert disable_commands_app.complete_has_helper_func.__doc__ == orig_complete.__doc__
4139
4140
4141 def test_disabled_completer_returns_empty(disable_commands_app: DisableCommandsApp) -> None:
4142 disable_commands_app.disable_command("has_helper_func", "Disabled")
4143 completions = disable_commands_app.complete_has_helper_func("", "has_helper_func ", 16, 16)
4144 assert len(completions) == 0
4145
4146
4147 def test_disabled_message_command_name(disable_commands_app: DisableCommandsApp) -> None:
4148 message_to_print = f"{COMMAND_NAME} is currently disabled"
4149 disable_commands_app.disable_command("has_helper_func", message_to_print)
4150
4151 _out, err = run_cmd(disable_commands_app, "has_helper_func")
4152 assert err[0].startswith("has_helper_func is currently disabled")
4153
4154
4155 def test_help_argparse_command_while_disabled(disable_commands_app: DisableCommandsApp) -> None:
4156 message_to_print = "This command is disabled"
4157 disable_commands_app.disable_command("argparse_command", message_to_print)
4158
4159 # help <command> should show the disabled message
4160 _out, err = run_cmd(disable_commands_app, "help argparse_command")
4161 assert err[0].startswith(message_to_print)
4162
4163 # Re-enabling should restore the real help
4164 disable_commands_app.enable_command("argparse_command")
4165 out, _err = run_cmd(disable_commands_app, "help argparse_command")
4166 assert "Usage: argparse_command" in out[0]
4167
4168
4169 def test_help_disabled_no_help_func(base_app: cmd2.Cmd) -> None:
4170 from cmd2.cmd2 import DisabledCommand
4171
4172 # Intentionally bypass disable_command() to test the fallback in do_help()
4173 command = "quit"
4174 command_func = cast(BoundCommandFunc, base_app.get_command_func(command))
4175 base_app.disabled_commands[command] = DisabledCommand(command_func=command_func, help_func=None, completer_func=None)
4176
4177 _out, err = run_cmd(base_app, f"help {command}")
4178 assert err[0].startswith(f"{command} is currently disabled.")
4179
4180
4181 def test_register_command_in_enabled_category(disable_commands_app) -> None:
4182 # Enable commands which are decorated with a category
4183 disable_commands_app.enable_category(DisableCommandSet.category_name)
4184
4185 # Enable commands in the default category
4186 disable_commands_app.enable_category(DisableCommandSet.DEFAULT_CATEGORY)
4187
4188 cs = DisableCommandSet()
4189 disable_commands_app.register_command_set(cs)
4190
4191 out, _err = run_cmd(disable_commands_app, "new_command")
4192 assert out[0] == "The real new_command"
4193
4194 out, _err = run_cmd(disable_commands_app, "cs_is_not_decorated")
4195 assert out[0] == "The real cs_is_not_decorated"
4196
4197
4198 def test_register_command_in_disabled_category(disable_commands_app) -> None:
4199 message_to_print = "CommandSet function is disabled"
4200
4201 # Disable commands which are decorated with a category
4202 disable_commands_app.disable_category(DisableCommandSet.category_name, message_to_print)
4203
4204 # Disable commands in the default category
4205 disable_commands_app.disable_category(DisableCommandSet.DEFAULT_CATEGORY, message_to_print)
4206
4207 cs = DisableCommandSet()
4208 disable_commands_app.register_command_set(cs)
4209
4210 _out, err = run_cmd(disable_commands_app, "new_command")
4211 assert err[0] == message_to_print
4212
4213 _out, err = run_cmd(disable_commands_app, "cs_is_not_decorated")
4214 assert err[0] == message_to_print
4215
4216
4217 def test_enable_enabled_category(disable_commands_app) -> None:
4218 # Test enabling a category that is not disabled
4219 saved_len = len(disable_commands_app.disabled_categories)
4220 disable_commands_app.enable_category("Test Category")
4221
4222 # The number of disabled categories should not have changed
4223 assert saved_len == len(disable_commands_app.disabled_categories)
4224
4225
4226 def test_disable_category_twice(disable_commands_app) -> None:
4227 saved_len = len(disable_commands_app.disabled_categories)
4228 message_to_print = "These commands are currently disabled"
4229 disable_commands_app.disable_category("Test Category", message_to_print)
4230
4231 # The number of disabled categories should have increased one
4232 new_len = len(disable_commands_app.disabled_categories)
4233 assert saved_len == new_len - 1
4234 saved_len = new_len
4235
4236 # Disable again and the length should not change
4237 disable_commands_app.disable_category("Test Category", message_to_print)
4238 new_len = len(disable_commands_app.disabled_categories)
4239 assert saved_len == new_len
4240
4241
4242 @pytest.mark.parametrize("silence_startup_script", [True, False])
4243 def test_startup_script(request, capsys, silence_startup_script) -> None:
4244 test_dir = os.path.dirname(request.module.__file__)
4245 startup_script = os.path.join(test_dir, ".cmd2rc")
4246 app = cmd2.Cmd(allow_cli_args=False, startup_script=startup_script, silence_startup_script=silence_startup_script)
4247 assert len(app._startup_commands) == 1
4248 app._startup_commands.append("quit")
4249 app.cmdloop()
4250
4251 out, _err = capsys.readouterr()
4252 if silence_startup_script:
4253 assert not out
4254 else:
4255 assert out
4256
4257 out, _err = run_cmd(app, "alias list")
4258 assert len(out) > 1
4259 assert "alias create ls" in out[0]
4260
4261
4262 @pytest.mark.parametrize("startup_script", odd_file_names)
4263 def test_startup_script_with_odd_file_names(startup_script) -> None:
4264 """Test file names with various patterns"""
4265 # Mock os.path.exists to trick cmd2 into adding this script to its startup commands
4266 saved_exists = os.path.exists
4267 os.path.exists = mock.MagicMock(name="exists", return_value=True)
4268
4269 app = cmd2.Cmd(allow_cli_args=False, startup_script=startup_script)
4270 assert len(app._startup_commands) == 1
4271 assert app._startup_commands[0] == f"run_script {su.quote(os.path.abspath(startup_script))}"
4272
4273 # Restore os.path.exists
4274 os.path.exists = saved_exists
4275
4276
4277 def test_command_parser_retrieval(outsim_app: cmd2.Cmd) -> None:
4278 # Pass something that isn't a method
4279 not_a_method = "just a string"
4280 assert outsim_app.command_parsers.get(not_a_method) is None
4281
4282 # Pass a non-command method
4283 assert outsim_app.command_parsers.get(outsim_app.__init__) is None
4284
4285
4286 def test_command_synonym_parser() -> None:
4287 # Make sure a command synonym returns the same parser as what it aliases
4288 class SynonymApp(cmd2.cmd2.Cmd):
4289 do_synonym = cmd2.cmd2.Cmd.do_help
4290
4291 app = SynonymApp()
4292
4293 synonym_parser = app.command_parsers.get(app.do_synonym)
4294 help_parser = app.command_parsers.get(app.do_help)
4295
4296 assert synonym_parser is not None
4297 assert synonym_parser is help_parser
4298
4299
4300 def test_custom_completekey_ctrl_k():
4301 from prompt_toolkit.keys import Keys
4302
4303 # Test setting a custom completekey to <CTRL> + K
4304 # In prompt_toolkit, this is 'c-k'
4305 app = cmd2.Cmd(completekey="c-k")
4306
4307 assert app.main_session.key_bindings is not None
4308
4309 # Check that we have a binding for c-k (Keys.ControlK)
4310 found = False
4311 for binding in app.main_session.key_bindings.bindings:
4312 # binding.keys is a tuple of keys
4313 if binding.keys == (Keys.ControlK,):
4314 found = True
4315 break
4316
4317 assert found, "Could not find binding for 'c-k' (Keys.ControlK) in session key bindings"
4318
4319
4320 def test_completekey_empty_string() -> None:
4321 # Test that an empty string for completekey defaults to DEFAULT_COMPLETEKEY
4322
4323 with mock.patch("cmd2.Cmd._create_main_session", autospec=True) as create_session_mock:
4324 create_session_mock.return_value = mock.MagicMock(spec=PromptSession)
4325
4326 app = cmd2.Cmd(completekey="")
4327 create_session_mock.assert_called_once()
4328 _, kwargs = create_session_mock.call_args
4329 assert kwargs["completekey"] == app.DEFAULT_COMPLETEKEY
4330
4331
4332 def test_create_main_session_exception(monkeypatch):
4333 # Mock PromptSession to raise ValueError on first call, then succeed
4334 valid_session_mock = mock.MagicMock(spec=PromptSession)
4335 mock_session = mock.MagicMock(side_effect=[ValueError, valid_session_mock])
4336 monkeypatch.setattr("cmd2.cmd2.PromptSession", mock_session)
4337
4338 # Mock isatty to ensure we enter the try block
4339 with (
4340 mock.patch("sys.stdin.isatty", return_value=True),
4341 mock.patch("sys.stdout.isatty", return_value=True),
4342 ):
4343 cmd2.Cmd()
4344
4345 # Check that fallback to DummyInput/Output happened
4346 assert mock_session.call_count == 2
4347
4348 # Check args of second call
4349 call_args = mock_session.call_args_list[1]
4350 kwargs = call_args[1]
4351 assert isinstance(kwargs["input"], DummyInput)
4352 assert isinstance(kwargs["output"], DummyOutput)
4353
4354
4355 @pytest.mark.skipif(
4356 not sys.platform.startswith("win"),
4357 reason="This tests how app.pager is set when running on Windows.",
4358 )
4359 def test_pager_on_windows(monkeypatch):
4360 app = cmd2.Cmd()
4361 assert app.pager == "more"
4362 assert app.pager_chop == "more"
4363
4364
4365 @pytest.mark.skipif(
4366 not sys.platform.startswith("win"),
4367 reason="This tests how Cmd._complete_users() behaves on Windows.",
4368 )
4369 def test_path_complete_users_windows(monkeypatch, base_app):
4370 # Mock os.path.expanduser and isdir
4371 monkeypatch.setattr("os.path.expanduser", lambda p: "/home/user" if p == "~user" else p)
4372 monkeypatch.setattr("os.path.isdir", lambda p: p == "/home/user")
4373
4374 matches = base_app.path_complete("~user", "cmd ~user", 0, 9)
4375 # Should contain ~user/ (or ~user\ depending on sep)
4376 # Since we didn't mock os.path.sep, it will use system separator.
4377 expected = "~user" + os.path.sep
4378 assert expected in matches
4379
4380
4381 def test_refresh_interval() -> None:
4382 # Test default value
4383 default_app = cmd2.Cmd()
4384 assert default_app.main_session.refresh_interval == 0.0
4385
4386 # Test custom value
4387 custom_app = cmd2.Cmd(refresh_interval=5.0)
4388 assert custom_app.main_session.refresh_interval == 5.0
4389
4390
4391 def test_enable_bottom_toolbar() -> None:
4392 # Test default
4393 default_app = cmd2.Cmd()
4394 assert default_app.main_session.bottom_toolbar is None
4395
4396 # Test True
4397 custom_app = cmd2.Cmd(enable_bottom_toolbar=True)
4398 assert custom_app.main_session.bottom_toolbar == custom_app.get_bottom_toolbar
4399
4400 # Test False
4401 custom_app = cmd2.Cmd(enable_bottom_toolbar=False)
4402 assert custom_app.main_session.bottom_toolbar is None
4403
4404
4405 def test_enable_rprompt() -> None:
4406 # Test default
4407 default_app = cmd2.Cmd()
4408 assert default_app.main_session.rprompt is None
4409
4410 # Test True
4411 custom_app = cmd2.Cmd(enable_rprompt=True)
4412 assert custom_app.main_session.rprompt == custom_app.get_rprompt
4413
4414 # Test False
4415 custom_app = cmd2.Cmd(enable_rprompt=False)
4416 assert custom_app.main_session.rprompt is None
4417
4418
4419 def test_get_bottom_toolbar(base_app: cmd2.Cmd) -> None:
4420 assert base_app.get_bottom_toolbar() is None
4421
4422
4423 def test_get_rprompt(base_app: cmd2.Cmd) -> None:
4424 assert base_app.get_rprompt() is None
4425
4426
4427 def test_multiline_complete_statement_keyboard_interrupt(multiline_app, monkeypatch):
4428 # Mock _read_command_line to raise KeyboardInterrupt
4429 read_command_mock = mock.MagicMock(name="_read_command_line", side_effect=KeyboardInterrupt)
4430 monkeypatch.setattr("cmd2.Cmd._read_command_line", read_command_mock)
4431
4432 # Mock poutput to verify ^C is printed
4433 poutput_mock = mock.MagicMock(name="poutput")
4434 monkeypatch.setattr(multiline_app, "poutput", poutput_mock)
4435
4436 with pytest.raises(exceptions.EmptyStatement):
4437 multiline_app._complete_statement("orate incomplete")
4438
4439 poutput_mock.assert_called_with("^C")
4440
4441
4442 def test_create_main_session_no_console_error(monkeypatch):
4443 from cmd2.cmd2 import NoConsoleScreenBufferError
4444
4445 # Mock PromptSession to raise NoConsoleScreenBufferError on first call, then succeed
4446 valid_session_mock = mock.MagicMock(spec=PromptSession)
4447 mock_session = mock.MagicMock(side_effect=[NoConsoleScreenBufferError, valid_session_mock])
4448 monkeypatch.setattr("cmd2.cmd2.PromptSession", mock_session)
4449
4450 # Mock isatty to ensure we enter the try block
4451 with (
4452 mock.patch("sys.stdin.isatty", return_value=True),
4453 mock.patch("sys.stdout.isatty", return_value=True),
4454 ):
4455 cmd2.Cmd()
4456
4457 # Check that fallback to DummyInput/Output happened
4458 assert mock_session.call_count == 2
4459
4460 # Check args of second call
4461 call_args = mock_session.call_args_list[1]
4462 kwargs = call_args[1]
4463 assert isinstance(kwargs["input"], DummyInput)
4464 assert isinstance(kwargs["output"], DummyOutput)
4465
4466
4467 def test_create_main_session_with_custom_tty() -> None:
4468 # Create a mock stdin with says it's a TTY
4469 custom_stdin = mock.MagicMock(spec=io.TextIOWrapper)
4470 custom_stdin.isatty.return_value = True
4471 assert custom_stdin is not sys.stdin
4472
4473 # Create a mock stdout with says it's a TTY
4474 custom_stdout = mock.MagicMock(spec=io.TextIOWrapper)
4475 custom_stdout.isatty.return_value = True
4476 assert custom_stdout is not sys.stdout
4477
4478 # Check if the streams were wrapped
4479 with (
4480 mock.patch("cmd2.cmd2.create_input") as mock_create_input,
4481 mock.patch("cmd2.cmd2.create_output") as mock_create_output,
4482 ):
4483 app = cmd2.Cmd()
4484 app.stdin = custom_stdin
4485 app.stdout = custom_stdout
4486 app._create_main_session(
4487 auto_suggest=True,
4488 completekey=app.DEFAULT_COMPLETEKEY,
4489 enable_bottom_toolbar=False,
4490 enable_rprompt=False,
4491 complete_in_thread=False,
4492 refresh_interval=0.0,
4493 )
4494
4495 mock_create_input.assert_called_once_with(stdin=custom_stdin)
4496 mock_create_output.assert_called_once_with(stdout=custom_stdout)
4497
4498
4499 def test_create_main_session_stdin_non_tty() -> None:
4500 # Set up a mock for a non-TTY stdin stream
4501 mock_stdin = mock.MagicMock(spec=io.TextIOWrapper)
4502 mock_stdin.isatty.return_value = False
4503
4504 app = cmd2.Cmd(stdin=mock_stdin)
4505 assert isinstance(app.main_session.input, DummyInput)
4506 assert isinstance(app.main_session.output, DummyOutput)
4507
4508
4509 def test_create_main_session_stdout_non_tty() -> None:
4510 # Set up a mock for a non-TTY stdout stream
4511 mock_stdout = mock.MagicMock(spec=io.TextIOWrapper)
4512 mock_stdout.isatty.return_value = False
4513
4514 app = cmd2.Cmd(stdout=mock_stdout)
4515 assert isinstance(app.main_session.input, DummyInput)
4516 assert isinstance(app.main_session.output, DummyOutput)
4517
4518
4519 def test_no_console_screen_buffer_error_dummy():
4520 from cmd2.cmd2 import NoConsoleScreenBufferError
4521
4522 # Check that it behaves like a normal exception
4523 err = NoConsoleScreenBufferError()
4524 assert isinstance(err, Exception)
4525
4526
4527 def test_read_command_line_dynamic_prompt(base_app: cmd2.Cmd) -> None:
4528 """Test that _read_command_line uses a dynamic prompt when provided prompt matches app.prompt"""
4529
4530 # Mock patch_stdout to prevent it from attempting to access the Windows
4531 # console buffer in a Windows test environment.
4532 with mock.patch("cmd2.cmd2.patch_stdout"):
4533 # Set input to something other than DummyInput so _read_raw_input()
4534 # will go down the TTY route.
4535 mock_session = mock.MagicMock()
4536 mock_session.input = mock.MagicMock()
4537 base_app.main_session = mock_session
4538 base_app._read_command_line(base_app.prompt)
4539
4540 # Check that mock_prompt was called with a callable for the prompt
4541 args, _ = mock_session.prompt.call_args
4542 prompt_arg = args[0]
4543 assert callable(prompt_arg)
4544
4545 # Verify the callable returns the expected ANSI formatted prompt
4546 from prompt_toolkit.formatted_text import ANSI
4547
4548 result = prompt_arg()
4549 assert isinstance(result, ANSI)
4550 assert result.value == ANSI(base_app.prompt).value
4551
4552
4553 def test_read_input_history_isolation(base_app: cmd2.Cmd) -> None:
4554 local_history = ["secret_command", "another_command"]
4555
4556 # Mock _read_raw_input to prevent actual blocking
4557 # We want to inspect the session object passed to it
4558 with mock.patch.object(base_app, "_read_raw_input") as mock_raw:
4559 mock_raw.return_value = "user_input"
4560
4561 base_app.read_input("prompt> ", history=local_history)
4562
4563 # Inspect the session used in the call
4564 args, _ = mock_raw.call_args
4565 passed_session = args[1]
4566
4567 # Verify the session's history contains our list
4568 loaded_history = list(passed_session.history.load_history_strings())
4569 assert "secret_command" in loaded_history
4570 assert "another_command" in loaded_history
4571
4572 # Verify the main app session was not touched
4573 # This is the crucial check for isolation
4574 main_history = base_app.main_session.history.get_strings()
4575 assert "secret_command" not in main_history
4576
4577
4578 @pytest.mark.skipif(
4579 sys.platform.startswith("win"),
4580 reason="Don't have a real Windows console with how we are currently running tests in GitHub Actions",
4581 )
4582 def test_pre_prompt_running_loop(base_app):
4583 # Test that pre_prompt runs with a running event loop.
4584 import asyncio
4585
4586 # Set up pipe input to feed data to prompt_toolkit
4587 with create_pipe_input() as pipe_input:
4588 # Create a new session with our pipe input because the input property is read-only
4589 base_app.main_session = PromptSession(
4590 input=pipe_input,
4591 output=DummyOutput(),
4592 history=base_app.main_session.history,
4593 completer=base_app.main_session.completer,
4594 )
4595
4596 loop_check = {"running": False}
4597
4598 def my_pre_prompt():
4599 try:
4600 asyncio.get_running_loop()
4601 loop_check["running"] = True
4602 except RuntimeError:
4603 loop_check["running"] = False
4604
4605 base_app.pre_prompt = my_pre_prompt
4606
4607 # Feed input to exit prompt immediately
4608 pipe_input.send_text("foo\n")
4609
4610 # Ensure self.session.prompt is used
4611 base_app._read_command_line("prompt> ")
4612
4613 assert loop_check["running"]
4614
4615
4616 def test_auto_suggest_true():
4617 """Test that auto_suggest=True initializes AutoSuggestFromHistory."""
4618 app = cmd2.Cmd(auto_suggest=True)
4619 assert isinstance(app.main_session.auto_suggest, AutoSuggestFromHistory)
4620
4621
4622 def test_auto_suggest_false():
4623 """Test that auto_suggest=False does not initialize AutoSuggestFromHistory."""
4624 app = cmd2.Cmd(auto_suggest=False)
4625 assert app.main_session.auto_suggest is None
4626
4627
4628 def test_auto_suggest_default():
4629 """Test that auto_suggest defaults to True."""
4630 app = cmd2.Cmd()
4631 assert isinstance(app.main_session.auto_suggest, AutoSuggestFromHistory)
4632
4633
4634 def test_subcommand_attachment() -> None:
4635 import argparse
4636
4637 class SubcmdApp(cmd2.Cmd):
4638 def __init__(self) -> None:
4639 super().__init__()
4640
4641 root_parser = cmd2.Cmd2ArgumentParser()
4642 root_parser.add_subparsers()
4643
4644 @cmd2.with_argparser(root_parser)
4645 def do_root(self, _args: argparse.Namespace) -> None:
4646 pass
4647
4648 app = SubcmdApp()
4649
4650 # Verify root exists and uses argparse
4651 root_parser = app.command_parsers.get(app.do_root)
4652 assert root_parser is not None
4653
4654 # Attach child to root
4655 child_parser = cmd2.Cmd2ArgumentParser(prog="child")
4656 child_parser.add_subparsers()
4657 child_record = SubcommandRecord(name="child", command="root", parser=child_parser, help="child help")
4658 app.attach_subcommand(child_record)
4659
4660 # Verify child was attached
4661 root_subparsers_action = root_parser.get_subparsers_action()
4662 assert "child" in root_subparsers_action._name_parser_map
4663 assert root_subparsers_action._name_parser_map["child"] is child_parser
4664
4665 # Attach grandchild to child
4666 grandchild_parser = cmd2.Cmd2ArgumentParser(prog="grandchild")
4667 grandchild_record = SubcommandRecord(name="grandchild", command="root child", parser=grandchild_parser)
4668 app.attach_subcommand(grandchild_record)
4669
4670 # Verify grandchild was attached
4671 child_subparsers_action = child_parser.get_subparsers_action()
4672 assert "grandchild" in child_subparsers_action._name_parser_map
4673
4674 # Detach grandchild
4675 detached_grandchild_info = app.detach_subcommand("root child", "grandchild")
4676 assert detached_grandchild_info.parser is grandchild_parser
4677 assert "grandchild" not in child_subparsers_action._name_parser_map
4678
4679 # Detach child
4680 detached_child_info = app.detach_subcommand("root", "child")
4681 assert detached_child_info.parser is child_parser
4682 assert "child" not in root_subparsers_action._name_parser_map
4683
4684
4685 def test_subcommand_attachment_errors() -> None:
4686 class SubcmdErrorApp(cmd2.Cmd):
4687 def __init__(self) -> None:
4688 super().__init__()
4689
4690 test_parser = cmd2.Cmd2ArgumentParser()
4691 test_parser.add_subparsers(required=True)
4692
4693 @cmd2.with_argparser(test_parser)
4694 def do_test(self, _statement: cmd2.Statement) -> None:
4695 pass
4696
4697 def do_no_argparse(self, _statement: cmd2.Statement) -> None:
4698 pass
4699
4700 app = SubcmdErrorApp()
4701
4702 # Test empty command
4703 sub_record = SubcommandRecord(name="sub", command="", parser=cmd2.Cmd2ArgumentParser())
4704 with pytest.raises(ValueError, match="Command path cannot be empty"):
4705 app.attach_subcommand(sub_record)
4706
4707 # Test non-existent command
4708 nonexistent_record = SubcommandRecord(name="sub", command="fake", parser=cmd2.Cmd2ArgumentParser())
4709 with pytest.raises(ValueError, match="Root command 'fake' does not exist"):
4710 app.attach_subcommand(nonexistent_record)
4711
4712 # Test command that doesn't use argparse
4713 no_argparse_record = SubcommandRecord(name="sub", command="no_argparse", parser=cmd2.Cmd2ArgumentParser())
4714 with pytest.raises(ValueError, match="Command 'no_argparse' does not use argparse"):
4715 app.attach_subcommand(no_argparse_record)
4716
4717 # Test duplicate subcommand
4718 duplicate_record = SubcommandRecord(name="sub", command="test", parser=cmd2.Cmd2ArgumentParser())
4719 app.attach_subcommand(duplicate_record)
4720 with pytest.raises(ValueError, match="Subcommand 'sub' already exists for 'test'"):
4721 app.attach_subcommand(duplicate_record)
4722
4723
4724 def test_detach_all_subcommands() -> None:
4725 import argparse
4726
4727 class RefactorApp(cmd2.Cmd):
4728 def __init__(self) -> None:
4729 super().__init__()
4730
4731 base_parser = cmd2.Cmd2ArgumentParser()
4732 base_parser.add_subparsers()
4733
4734 @cmd2.with_argparser(base_parser)
4735 def do_base(self, _: argparse.Namespace) -> None:
4736 pass
4737
4738 app = RefactorApp()
4739
4740 child1 = cmd2.Cmd2ArgumentParser()
4741 child2 = cmd2.Cmd2ArgumentParser()
4742
4743 child1_record = SubcommandRecord(name="child1", command="base", parser=child1)
4744 child2_record = SubcommandRecord(name="child2", command="base", parser=child2)
4745
4746 app.attach_subcommand(child1_record)
4747 app.attach_subcommand(child2_record)
4748
4749 removed = app.detach_all_subcommands("base")
4750 assert len(removed) == 2
4751
4752 root_parser = cast(cmd2.Cmd2ArgumentParser, app.command_parsers.get(app.do_base))
4753 subparsers_action = root_parser.get_subparsers_action()
4754 assert not subparsers_action._name_parser_map