Skip to content

Commit 7a2de44

Browse files
committed
test(argparse): add coverage for fallback to flags with empty positional
Added a unit test 'test_autcomp_fallback_to_flags_nargs0' to cover the logic in 'ArgparseCompleter' that falls back to flag completion when a positional argument has reached its maximum number of values and the current input is empty. This was achieved by manually patching the 'nargs' attribute of a positional action to 0.
1 parent 4f0b5f1 commit 7a2de44

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

tests/test_argparse_completer.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1347,3 +1347,33 @@ def test_add_parser_custom_completer() -> None:
13471347

13481348
custom_completer_parser = subparsers.add_parser(name="custom_completer", ap_completer_type=CustomCompleter)
13491349
assert custom_completer_parser.get_ap_completer_type() is CustomCompleter # type: ignore[attr-defined]
1350+
1351+
1352+
def test_autcomp_fallback_to_flags_nargs0(ac_app) -> None:
1353+
"""Test fallback to flags when a positional argument has nargs=0 (using manual patching)"""
1354+
from cmd2.argparse_completer import (
1355+
ArgparseCompleter,
1356+
)
1357+
1358+
parser = Cmd2ArgumentParser()
1359+
# Add a positional argument
1360+
action = parser.add_argument('pos')
1361+
# Add a flag
1362+
parser.add_argument('-f', '--flag', action='store_true', help='a flag')
1363+
1364+
# Manually change nargs to 0 AFTER adding it to bypass argparse validation during add_argument.
1365+
# This allows us to hit the fallback-to-flags logic in _handle_last_token where pos_arg_state.max is 0.
1366+
action.nargs = 0
1367+
1368+
ac = ArgparseCompleter(parser, ac_app)
1369+
1370+
text = ''
1371+
line = 'cmd '
1372+
endidx = len(line)
1373+
begidx = endidx - len(text)
1374+
tokens = ['']
1375+
1376+
# This should hit the fallback to flags in _handle_last_token because pos has max=0 and count=0
1377+
results = ac.complete(text, line, begidx, endidx, tokens)
1378+
1379+
assert any(item == '-f' for item in results)

0 commit comments

Comments
 (0)