diff --git a/pythainlp/cli/__init__.py b/pythainlp/cli/__init__.py index e7001f5bb..83995f9a5 100644 --- a/pythainlp/cli/__init__.py +++ b/pythainlp/cli/__init__.py @@ -5,7 +5,7 @@ import io import sys -from argparse import ArgumentParser +from argparse import ArgumentError, ArgumentParser sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8") sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8") @@ -23,6 +23,14 @@ def make_usage(command: str) -> dict: def exit_if_empty(command: str, parser: ArgumentParser) -> None: + """Print help and exit if command is empty. + + :param command: command from command line + :type command: str + :param parser: parser object of the app + :type parser: ArgumentParser + """ if not command: - parser.print_help() - sys.exit(0) + if parser: + parser.print_help() + raise ArgumentError(None, "No command provided.") diff --git a/tests/test_cli.py b/tests/test_cli.py index 15b4750bb..eb68668ac 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -13,6 +13,10 @@ class CliTestCase(unittest.TestCase): + def test_cli(self): + with self.assertRaises((ArgumentError, SystemExit)): + cli.exit_if_empty("", None) + def test_cli_main(self): # call with no argument, should exit with 2 with self.assertRaises(SystemExit) as ex: @@ -20,12 +24,10 @@ def test_cli_main(self): self.assertEqual(ex.exception.code, 2) with self.assertRaises((ArgumentError, SystemExit)): - self.assertIsNone(__main__.main(["thainlp"])) + __main__.main(["thainlp"]) with self.assertRaises((ArgumentError, SystemExit)): - self.assertIsNone( - __main__.main(["thainlp", "NOT_EXIST", "command"]) - ) + __main__.main(["thainlp", "NOT_EXIST", "command"]) self.assertIsNone(__main__.main(["thainlp", "data", "path"]))