Skip to content

Commit 1ca7260

Browse files
authored
Merge pull request #176 from hananmd/fix-verbose-without-command
Fix: require subcommand to prevent KeyError with -v/--verbose (closes…
2 parents 029ccac + e5f711f commit 1ca7260

2 files changed

Lines changed: 14 additions & 7 deletions

File tree

‎fixit/cli.py‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ def build_parser() -> argparse.ArgumentParser:
281281
action="store_true",
282282
help="enable verbose logging",
283283
)
284-
sub = parser.add_subparsers(dest="command")
284+
sub = parser.add_subparsers(dest="command", required=True)
285285

286286
wc = sub.add_parser("wc", help="count words, lines and characters")
287287
wc.add_argument("text", nargs="?")
@@ -401,10 +401,6 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
401401
if argv is None:
402402
argv = sys.argv[1:]
403403

404-
if not argv:
405-
parser.print_usage(sys.stderr)
406-
parser.exit(2)
407-
408404
try:
409405
args = parser.parse_args(argv)
410406
if args.command is None:
@@ -418,8 +414,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int:
418414
force=True,
419415
)
420416

421-
if args.command is not None:
422-
logger.debug("running command %s", args.command)
417+
logger.debug("running command %s", args.command)
423418

424419
if args.command is None:
425420
parser.print_usage(sys.stderr)

‎tests/test_cli.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,18 @@ def test_no_command_shows_error(capsys):
217217
assert "usage" in captured.err.lower()
218218

219219

220+
@pytest.mark.parametrize("flag", ["-v", "--verbose"])
221+
def test_verbose_without_command_shows_usage_error(capsys, flag):
222+
with pytest.raises(SystemExit) as exc_info:
223+
main([flag])
224+
225+
assert exc_info.value.code == 2
226+
227+
captured = capsys.readouterr()
228+
assert "usage" in captured.err.lower()
229+
assert captured.out == ""
230+
231+
220232
def test_help_shows_examples(capsys):
221233
parser = build_parser()
222234

0 commit comments

Comments
 (0)