Skip to content

Commit 0248eaa

Browse files
committed
Added unit test for Cmd2ArgparseError
1 parent b3eafe7 commit 0248eaa

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

tests/test_plugin.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
Test plugin infrastructure and hooks.
55
"""
6+
import argparse
67
import sys
78

89
import pytest
@@ -14,7 +15,7 @@
1415
from unittest import mock
1516

1617
import cmd2
17-
from cmd2 import exceptions, plugin
18+
from cmd2 import exceptions, plugin, Cmd2ArgumentParser, with_argparser
1819

1920

2021
class Plugin:
@@ -254,6 +255,14 @@ def do_say(self, statement):
254255
"""Repeat back the arguments"""
255256
self.poutput(statement)
256257

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+
257266
###
258267
#
259268
# test pre and postloop hooks
@@ -836,3 +845,31 @@ def test_cmdfinalization_hook_exception(capsys):
836845
assert out == 'hello\n'
837846
assert err
838847
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

Comments
 (0)