Skip to content

Commit a1c99e0

Browse files
committed
Fixed bug in annotated.py where it used a stale copy of DEFAULT_ARGUMENT_PARSER.
Added test for set_default_argument_parser().
1 parent 5413585 commit a1c99e0

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

cmd2/annotated.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,6 @@ def do_paint(
212212

213213
from . import constants
214214
from .argparse_utils import (
215-
DEFAULT_ARGUMENT_PARSER,
216215
ArgparseCommandSpec,
217216
Cmd2ArgumentParser,
218217
SubcommandSpec,
@@ -1968,7 +1967,9 @@ def build_parser_from_function(
19681967
:param parser_kwargs: forwarded [`Cmd2ParserKwargs`][cmd2.annotated.Cmd2ParserKwargs]
19691968
:return: a fully configured ``Cmd2ArgumentParser``
19701969
"""
1971-
parser_cls = parser_class or DEFAULT_ARGUMENT_PARSER
1970+
from . import argparse_utils
1971+
1972+
parser_cls = parser_class or argparse_utils.DEFAULT_ARGUMENT_PARSER
19721973
if "description" not in parser_kwargs:
19731974
auto_description = _docstring_first_paragraph(func.__doc__)
19741975
if auto_description is not None:

tests/test_argparse_utils.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -863,3 +863,30 @@ def test_deprecated_subcommand() -> None:
863863
# Verify it was removed from _deprecated set
864864
assert "old" not in subparsers_action._deprecated # type: ignore[attr-defined]
865865
assert "old_alias" not in subparsers_action._deprecated # type: ignore[attr-defined]
866+
867+
868+
def test_set_default_argument_parser() -> None:
869+
"""Test altering the app-wide default Cmd2ArgumentParser class"""
870+
871+
class CustomParser(Cmd2ArgumentParser):
872+
pass
873+
874+
try:
875+
# Check the default parser type
876+
assert argparse_utils.DEFAULT_ARGUMENT_PARSER is Cmd2ArgumentParser
877+
878+
default_app = cmd2.Cmd()
879+
default_alias_parser = default_app.command_parsers.get(default_app.do_alias)
880+
assert type(default_alias_parser) is Cmd2ArgumentParser
881+
882+
# Set a custom default parser type
883+
argparse_utils.set_default_argument_parser(CustomParser)
884+
assert argparse_utils.DEFAULT_ARGUMENT_PARSER is CustomParser
885+
886+
custom_app = cmd2.Cmd()
887+
custom_alias_parser = custom_app.command_parsers.get(custom_app.do_alias)
888+
assert type(custom_alias_parser) is CustomParser
889+
890+
finally:
891+
# Restore the original parser
892+
argparse_utils.set_default_argument_parser(Cmd2ArgumentParser)

0 commit comments

Comments
 (0)