Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test and slightly extend the Python command-line interface #447

Merged
merged 2 commits into from
Nov 20, 2023
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
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 == '-->'
Loading