From de5a3347ffbea243ef0a9e534d5c5c47031e1814 Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Mon, 20 Nov 2023 03:09:35 -0500 Subject: [PATCH] Test and slightly extend the Python command-line interface (#447) * Add a `--times` argument to the Python CLI I meant to include this previously, but I forgot. * Test the Python command-line interface --- src/python/code/gnoll/__main__.py | 35 ++++++++++++++++++++++--------- tests/python/test_cli.py | 20 ++++++++++++++++++ 2 files changed, 45 insertions(+), 10 deletions(-) create mode 100644 tests/python/test_cli.py diff --git a/src/python/code/gnoll/__main__.py b/src/python/code/gnoll/__main__.py index 3f3e83e4a..7ae6b78b5 100644 --- a/src/python/code/gnoll/__main__.py +++ b/src/python/code/gnoll/__main__.py @@ -34,6 +34,14 @@ def parse_cmdline_args(args): action='store_true', help='show a breakdown into individual dice' ) + g.add_argument( + '-n', + '--times', + metavar='N', + type=int, + default=1, + help='execute the entire expression N times' + ) g.add_argument( '--no-builtins', action='store_true', @@ -71,22 +79,29 @@ def parse_cmdline_args(args): return a -def main(EXPR, no_builtins, **kwargs): +def main(EXPR, times, no_builtins, **kwargs): """ The entry point for gnoll when called via `python -m gnoll` @param EXPR - the expression + @param times - number of times to execute @param no_builtins - a flag to disable builtins @param **kwargs - other key word arguments to be passed to gnoll.roll """ - _, [[result]], breakdown = gnoll.roll( - EXPR, - builtins=not no_builtins, - **kwargs) - if breakdown: - print(breakdown[0], '-->', result) - else: - print(result) + for _ in range(times): + _, [[result]], breakdown = gnoll.roll( + EXPR, + builtins=not no_builtins, + **kwargs) + yield (breakdown[0], '-->', result) if breakdown else (result,) + + +def main_with_args(args): + """Parse the commandline args and then run `main` + @param args - the arguments from the commandline (excluding the python3 call) + """ + yield from main(**vars(parse_cmdline_args(args))) if __name__ == '__main__': - main(**vars(parse_cmdline_args(sys.argv[1:]))) + for line in main_with_args(sys.argv[1:]): + print(*line) diff --git a/tests/python/test_cli.py b/tests/python/test_cli.py new file mode 100644 index 000000000..b5c4473f2 --- /dev/null +++ b/tests/python/test_cli.py @@ -0,0 +1,20 @@ +import gnoll.__main__ + + +m = lambda *x: list(gnoll.__main__.main_with_args(x)) + + +def test_cli(): + + [[r]] = m('1d4') + assert isinstance(r, int) + + [[(die1, die2), a, r]] = m('2d4', '--breakdown') + assert all((isinstance(x, int) for x in [die1, die2, r])) + assert a == '-->' + + executions = m('4d6kh3', '+', '1', '--breakdown', '--times', '6', '--no-builtins') + assert len(executions) == 6 + for (die1, die2, die3, die4), a, r in executions: + assert all((isinstance(x, int) for x in [die1, die2, die3, die4, r])) + assert a == '-->'