summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--hazwaz/command.py30
-rw-r--r--tests/test_command.py25
2 files changed, 53 insertions, 2 deletions
diff --git a/hazwaz/command.py b/hazwaz/command.py
index 14a8a52..2bfa2b9 100644
--- a/hazwaz/command.py
+++ b/hazwaz/command.py
@@ -57,9 +57,22 @@ class MainCommand:
sub_parser.set_defaults(func=sub._main)
def main(self, args):
+ """
+ The main function for a command with no subcommands.
+
+ This default implementation that simply prints the help is good
+ for most cases when there are subcommands and running the bare
+ command doesn't do anything.
+ """
self.parser.print_help()
def add_arguments(self, parser: argparse.ArgumentParser):
+ """
+ Add argparse arguments to an existing parser.
+
+ If you need to override this method, you probably want to call
+ super().add_arguments(parser) to add the default arguments.
+ """
group = parser.add_mutually_exclusive_group()
group.add_argument(
'--verbose', '-v',
@@ -75,9 +88,9 @@ class MainCommand:
def run(self):
self.args = self.parser.parse_args()
- if self.args.debug:
+ if getattr(self.args, "debug", False):
logger.setLevel(logging.DEBUG)
- elif self.args.verbose:
+ elif getattr(self.args, "verbose", False):
logger.setLevel(logging.INFO)
else:
logger.setLevel(logging.WARNING)
@@ -103,4 +116,17 @@ class Command:
self.main()
def add_arguments(self, parser: argparse.ArgumentParser):
+ """
+ Add argparse arguments to an existing parser.
+
+ Override this method to add arguments to a subcommand.
+ """
pass
+
+ def main(self):
+ """
+ Main code of this subcommand.
+
+ Override this method to implement the actual program.
+ """
+ raise NotImplementedError
diff --git a/tests/test_command.py b/tests/test_command.py
index f4e93bb..2f9850d 100644
--- a/tests/test_command.py
+++ b/tests/test_command.py
@@ -44,6 +44,25 @@ class MyCommand(hazwaz.MainCommand):
)
+class MyCommandWithNoVerbose(hazwaz.MainCommand):
+ """
+ A command that always talks.
+
+ This command doesn't have the --verbose and --debug arguments.
+
+ """
+
+ def add_arguments(self, parser):
+ # we override add_arguments and don't call
+ # super().add_arguments(parser) so that --verbose and --debug
+ # are missing.
+ parser.add_argument(
+ "--foo",
+ action="store_true",
+ help="foobar things",
+ )
+
+
class testCommand(unittest.TestCase):
def _run_with_argv(self, cmd, argv):
stream = {
@@ -133,6 +152,12 @@ class testCommand(unittest.TestCase):
])
self.assertEqual(stream["stdout"].getvalue(), "Hello World\n")
+ def test_run_no_verbose(self):
+ cmd = MyCommandWithNoVerbose()
+ cmd_help = cmd.parser.format_help()
+ stream = self._run_with_argv(cmd, ["mycommand"])
+ self.assertEqual(stream["stdout"].getvalue(), cmd_help)
+
if __name__ == '__main__':
unittest.main()