diff options
author | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2020-03-12 22:11:57 -0400 |
---|---|---|
committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2020-03-12 22:11:57 -0400 |
commit | 0248eaa50ebd5dc1a9298d25a7649c3a1e31b583 (patch) | |
tree | 823b8874ae60ea6617db1636fd836803297ae872 /tests/test_plugin.py | |
parent | b3eafe71b400a7a48bda5a456d53a9433ef838dd (diff) | |
download | cmd2-git-0248eaa50ebd5dc1a9298d25a7649c3a1e31b583.tar.gz |
Added unit test for Cmd2ArgparseError
Diffstat (limited to 'tests/test_plugin.py')
-rw-r--r-- | tests/test_plugin.py | 39 |
1 files changed, 38 insertions, 1 deletions
diff --git a/tests/test_plugin.py b/tests/test_plugin.py index c118b60d..8d0ae8a7 100644 --- a/tests/test_plugin.py +++ b/tests/test_plugin.py @@ -3,6 +3,7 @@ """ Test plugin infrastructure and hooks. """ +import argparse import sys import pytest @@ -14,7 +15,7 @@ except ImportError: from unittest import mock import cmd2 -from cmd2 import exceptions, plugin +from cmd2 import exceptions, plugin, Cmd2ArgumentParser, with_argparser class Plugin: @@ -254,6 +255,14 @@ class PluggedApp(Plugin, cmd2.Cmd): """Repeat back the arguments""" self.poutput(statement) + parser = Cmd2ArgumentParser(description="Test parser") + parser.add_argument("my_arg", help="some help text") + + @with_argparser(parser) + def do_argparse_cmd(self, namespace: argparse.Namespace): + """Repeat back the arguments""" + self.poutput(namespace.__statement__) + ### # # test pre and postloop hooks @@ -836,3 +845,31 @@ def test_cmdfinalization_hook_exception(capsys): assert out == 'hello\n' assert err assert app.called_cmdfinalization == 1 + + +def test_cmd2_argparse_exception(capsys): + """ + Verify Cmd2ArgparseExceptions raised after calling a command prevent postcmd events from + running but do not affect cmdfinalization events + """ + app = PluggedApp() + app.register_postcmd_hook(app.postcmd_hook) + app.register_cmdfinalization_hook(app.cmdfinalization_hook) + + # First generate no exception and make sure postcmd_hook, postcmd, and cmdfinalization_hook run + app.onecmd_plus_hooks('argparse_cmd arg_val') + out, err = capsys.readouterr() + assert out == 'arg_val\n' + assert not err + assert app.called_postcmd == 2 + assert app.called_cmdfinalization == 1 + + app.reset_counters() + + # Next cause an argparse exception and verify no postcmd stuff runs but cmdfinalization_hook still does + app.onecmd_plus_hooks('argparse_cmd') + out, err = capsys.readouterr() + assert not out + assert "Error: the following arguments are required: my_arg" in err + assert app.called_postcmd == 0 + assert app.called_cmdfinalization == 1 |