|
3 | 3 | """
|
4 | 4 | Test plugin infrastructure and hooks.
|
5 | 5 | """
|
| 6 | +import argparse |
6 | 7 | import sys
|
7 | 8 |
|
8 | 9 | import pytest
|
|
14 | 15 | from unittest import mock
|
15 | 16 |
|
16 | 17 | import cmd2
|
17 |
| -from cmd2 import exceptions, plugin |
| 18 | +from cmd2 import exceptions, plugin, Cmd2ArgumentParser, with_argparser |
18 | 19 |
|
19 | 20 |
|
20 | 21 | class Plugin:
|
@@ -254,6 +255,14 @@ def do_say(self, statement):
|
254 | 255 | """Repeat back the arguments"""
|
255 | 256 | self.poutput(statement)
|
256 | 257 |
|
| 258 | + parser = Cmd2ArgumentParser(description="Test parser") |
| 259 | + parser.add_argument("my_arg", help="some help text") |
| 260 | + |
| 261 | + @with_argparser(parser) |
| 262 | + def do_argparse_cmd(self, namespace: argparse.Namespace): |
| 263 | + """Repeat back the arguments""" |
| 264 | + self.poutput(namespace.__statement__) |
| 265 | + |
257 | 266 | ###
|
258 | 267 | #
|
259 | 268 | # test pre and postloop hooks
|
@@ -836,3 +845,31 @@ def test_cmdfinalization_hook_exception(capsys):
|
836 | 845 | assert out == 'hello\n'
|
837 | 846 | assert err
|
838 | 847 | assert app.called_cmdfinalization == 1
|
| 848 | + |
| 849 | + |
| 850 | +def test_cmd2_argparse_exception(capsys): |
| 851 | + """ |
| 852 | + Verify Cmd2ArgparseExceptions raised after calling a command prevent postcmd events from |
| 853 | + running but do not affect cmdfinalization events |
| 854 | + """ |
| 855 | + app = PluggedApp() |
| 856 | + app.register_postcmd_hook(app.postcmd_hook) |
| 857 | + app.register_cmdfinalization_hook(app.cmdfinalization_hook) |
| 858 | + |
| 859 | + # First generate no exception and make sure postcmd_hook, postcmd, and cmdfinalization_hook run |
| 860 | + app.onecmd_plus_hooks('argparse_cmd arg_val') |
| 861 | + out, err = capsys.readouterr() |
| 862 | + assert out == 'arg_val\n' |
| 863 | + assert not err |
| 864 | + assert app.called_postcmd == 2 |
| 865 | + assert app.called_cmdfinalization == 1 |
| 866 | + |
| 867 | + app.reset_counters() |
| 868 | + |
| 869 | + # Next cause an argparse exception and verify no postcmd stuff runs but cmdfinalization_hook still does |
| 870 | + app.onecmd_plus_hooks('argparse_cmd') |
| 871 | + out, err = capsys.readouterr() |
| 872 | + assert not out |
| 873 | + assert "Error: the following arguments are required: my_arg" in err |
| 874 | + assert app.called_postcmd == 0 |
| 875 | + assert app.called_cmdfinalization == 1 |
0 commit comments