Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions pythainlp/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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.")
10 changes: 6 additions & 4 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,21 @@


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:
__main__.main()
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"]))

Expand Down