summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/conftest.py8
-rw-r--r--tests/test_autocompletion.py6
-rw-r--r--tests/test_cmd2.py96
3 files changed, 98 insertions, 12 deletions
diff --git a/tests/conftest.py b/tests/conftest.py
index 9ca506af..fb049a8c 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -42,14 +42,14 @@ load Runs commands in script file that is encoded as either ASCII
py Invoke python command, shell, or script
pyscript Runs a python script file inside the console
quit Exits this application.
-set Sets a settable parameter or shows current settings of parameters.
+set Sets a settable parameter or shows current settings of parameters
shell Execute a command as if at the OS prompt.
shortcuts Lists shortcuts (aliases) available.
unalias Unsets aliases
"""
# Help text for the history command
-HELP_HISTORY = """usage: history [-h] [-r | -e | -s | -o FILE | -t TRANSCRIPT | -c] [arg]
+HELP_HISTORY = """Usage: history [arg] [-h] [-r | -e | -s | -o FILE | -t TRANSCRIPT | -c]
View, run, edit, save, or clear previously entered commands.
@@ -65,9 +65,9 @@ optional arguments:
-r, --run run selected history items
-e, --edit edit and then run selected history items
-s, --script script format; no separation lines
- -o FILE, --output-file FILE
+ -o, --output-file FILE
output commands to a script file
- -t TRANSCRIPT, --transcript TRANSCRIPT
+ -t, --transcript TRANSCRIPT
output commands and results to a transcript file
-c, --clear clears all history
"""
diff --git a/tests/test_autocompletion.py b/tests/test_autocompletion.py
index e0a71831..8aa26e0e 100644
--- a/tests/test_autocompletion.py
+++ b/tests/test_autocompletion.py
@@ -19,8 +19,8 @@ def cmd2_app():
SUGGEST_HELP = '''Usage: suggest -t {movie, show} [-h] [-d DURATION{1..2}]
-Suggest command demonstrates argparse customizations See hybrid_suggest and
-orig_suggest to compare the help output.
+Suggest command demonstrates argparse customizations.
+See hybrid_suggest and orig_suggest to compare the help output.
required arguments:
-t, --type {movie, show}
@@ -59,7 +59,7 @@ def test_help_required_group(cmd2_app, capsys):
assert out1 == out2
assert out1[0].startswith('Usage: suggest')
assert out1[1] == ''
- assert out1[2].startswith('Suggest command demonstrates argparse customizations ')
+ assert out1[2].startswith('Suggest command demonstrates argparse customizations.')
assert out1 == normalize(SUGGEST_HELP)
diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py
index efdfee7e..85e6c2f8 100644
--- a/tests/test_cmd2.py
+++ b/tests/test_cmd2.py
@@ -63,7 +63,7 @@ def test_base_argparse_help(base_app, capsys):
out2 = run_cmd(base_app, 'help set')
assert out1 == out2
- assert out1[0].startswith('usage: set')
+ assert out1[0].startswith('Usage: set')
assert out1[1] == ''
assert out1[2].startswith('Sets a settable parameter')
@@ -72,10 +72,8 @@ def test_base_invalid_option(base_app, capsys):
out, err = capsys.readouterr()
out = normalize(out)
err = normalize(err)
- assert len(err) == 3
- assert len(out) == 15
assert 'Error: unrecognized arguments: -z' in err[0]
- assert out[0] == 'usage: set [-h] [-a] [-l] [settable [settable ...]]'
+ assert out[0] == 'Usage: set settable{0..2} [-h] [-a] [-l]'
def test_base_shortcuts(base_app):
out = run_cmd(base_app, 'shortcuts')
@@ -1252,7 +1250,7 @@ load Runs commands in script file that is encoded as either ASCII
py Invoke python command, shell, or script
pyscript Runs a python script file inside the console
quit Exits this application.
-set Sets a settable parameter or shows current settings of parameters.
+set Sets a settable parameter or shows current settings of parameters
shell Execute a command as if at the OS prompt.
shortcuts Lists shortcuts (aliases) available.
unalias Unsets aliases
@@ -1918,6 +1916,94 @@ def test_bad_history_file_path(capsys, request):
assert 'readline cannot read' in err
+def test_get_all_commands(base_app):
+ # Verify that the base app has the expected commands
+ commands = base_app.get_all_commands()
+ expected_commands = ['_relative_load', 'alias', 'edit', 'eof', 'eos', 'help', 'history', 'load', 'py', 'pyscript',
+ 'quit', 'set', 'shell', 'shortcuts', 'unalias']
+ assert commands == expected_commands
+
+def test_get_help_topics(base_app):
+ # Verify that the base app has no additional help_foo methods
+ custom_help = base_app.get_help_topics()
+ assert len(custom_help) == 0
+
+
+class ReplWithExitCode(cmd2.Cmd):
+ """ Example cmd2 application where we can specify an exit code when existing."""
+
+ def __init__(self):
+ super().__init__()
+
+ @cmd2.with_argument_list
+ def do_exit(self, arg_list) -> bool:
+ """Exit the application with an optional exit code.
+
+Usage: exit [exit_code]
+ Where:
+ * exit_code - integer exit code to return to the shell
+"""
+ # If an argument was provided
+ if arg_list:
+ try:
+ self.exit_code = int(arg_list[0])
+ except ValueError:
+ self.perror("{} isn't a valid integer exit code".format(arg_list[0]))
+ self.exit_code = -1
+
+ self._should_quit = True
+ return self._STOP_AND_EXIT
+
+ def postloop(self) -> None:
+ """Hook method executed once when the cmdloop() method is about to return."""
+ code = self.exit_code if self.exit_code is not None else 0
+ self.poutput('exiting with code: {}'.format(code))
+
+@pytest.fixture
+def exit_code_repl():
+ app = ReplWithExitCode()
+ return app
+
+def test_exit_code_default(exit_code_repl):
+ # Create a cmd2.Cmd() instance and make sure basic settings are like we want for test
+ app = exit_code_repl
+ app.use_rawinput = True
+ app.stdout = StdOut()
+
+ # Mock out the input call so we don't actually wait for a user's response on stdin
+ m = mock.MagicMock(name='input', return_value='exit')
+ builtins.input = m
+
+ # Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
+ testargs = ["prog"]
+ expected = 'exiting with code: 0\n'
+ with mock.patch.object(sys, 'argv', testargs):
+ # Run the command loop
+ app.cmdloop()
+ out = app.stdout.buffer
+ assert out == expected
+
+def test_exit_code_nonzero(exit_code_repl):
+ # Create a cmd2.Cmd() instance and make sure basic settings are like we want for test
+ app = exit_code_repl
+ app.use_rawinput = True
+ app.stdout = StdOut()
+
+ # Mock out the input call so we don't actually wait for a user's response on stdin
+ m = mock.MagicMock(name='input', return_value='exit 23')
+ builtins.input = m
+
+ # Need to patch sys.argv so cmd2 doesn't think it was called with arguments equal to the py.test args
+ testargs = ["prog"]
+ expected = 'exiting with code: 23\n'
+ with mock.patch.object(sys, 'argv', testargs):
+ # Run the command loop
+ with pytest.raises(SystemExit):
+ app.cmdloop()
+ out = app.stdout.buffer
+ assert out == expected
+
+
class ColorsApp(cmd2.Cmd):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)