Skip to content

Commit

Permalink
Test and slightly extend the Python command-line interface (#447)
Browse files Browse the repository at this point in the history
* Add a `--times` argument to the Python CLI

I meant to include this previously, but I forgot.

* Test the Python command-line interface
  • Loading branch information
Kodiologist committed Nov 20, 2023
1 parent 9cf914a commit de5a334
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 10 deletions.
35 changes: 25 additions & 10 deletions src/python/code/gnoll/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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)
20 changes: 20 additions & 0 deletions tests/python/test_cli.py
Original file line number Diff line number Diff line change
@@ -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 == '-->'

0 comments on commit de5a334

Please sign in to comment.