Skip to content

Commit

Permalink
cli: add subcommand functionality to commands
Browse files Browse the repository at this point in the history
Signed-off-by: Renan Rodrigo <[email protected]>
  • Loading branch information
renanrodrigo committed Jul 13, 2024
1 parent 8bf4ef9 commit fec8fec
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
12 changes: 12 additions & 0 deletions uaclient/cli/commands.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
from typing import Callable, Iterable, Optional, Union

from uaclient import messages
from uaclient.cli.constants import NAME, USAGE_TMPL


Expand Down Expand Up @@ -79,6 +80,7 @@ def __init__(
action: Callable = lambda *args, **kwargs: None,
preserve_description: bool = False,
argument_groups: Iterable[ProArgumentGroup] = (),
subcommands: Iterable["ProCommand"] = (),
):
self.name = name
self.help = help
Expand All @@ -87,6 +89,7 @@ def __init__(
self.action = action
self.preserve_description = preserve_description
self.argument_groups = argument_groups
self.subcommands = subcommands

def register(self, subparsers: argparse._SubParsersAction):
self.parser = subparsers.add_parser(
Expand All @@ -102,3 +105,12 @@ def register(self, subparsers: argparse._SubParsersAction):
argument_group.register(self.parser)

self.parser.set_defaults(action=self.action)

if self.subcommands:
subparsers = self.parser.add_subparsers(
title=messages.CLI_AVAILABLE_COMMANDS,
dest="command",
metavar="",
)
for command in self.subcommands:
command.register(subparsers)
23 changes: 23 additions & 0 deletions uaclient/cli/tests/test_cli_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,29 @@ def test_command_register(self):
mock.call(action=example_command.action)
] == example_command.parser.set_defaults.call_args_list

def test_has_subcommands(self):
mock_subparsers = mock.MagicMock()

example_subcommand1 = mock.MagicMock()
example_subcommand2 = mock.MagicMock()

example_command = ProCommand(
"example",
help="help",
description="description",
subcommands=[example_subcommand1, example_subcommand2],
)

example_command.register(mock_subparsers)

inner_subparsers = example_command.parser.add_subparsers.return_value
assert [
mock.call(inner_subparsers)
] == example_subcommand1.register.call_args_list
assert [
mock.call(inner_subparsers)
] == example_subcommand2.register.call_args_list


class TestProArgument:
def test_argument_register(self):
Expand Down

0 comments on commit fec8fec

Please sign in to comment.