Skip to content

Commit

Permalink
Added test showing that subcommands are dispatched, and two failing t…
Browse files Browse the repository at this point in the history
…ests for issue click-contrib#92.
  • Loading branch information
flacoste committed Mar 29, 2023
1 parent 740665c commit 0960d14
Showing 1 changed file with 75 additions and 2 deletions.
77 changes: 75 additions & 2 deletions tests/test_repl.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
import contextlib
import sys

import click
import click_repl
import pytest

from io import StringIO


@contextlib.contextmanager
def mock_stdin(text):
old_stdin = sys.stdin
try:
sys.stdin = StringIO(text)
yield sys.stdin
finally:
sys.stdin = old_stdin


def test_simple_repl():
@click.group()
Expand All @@ -21,7 +36,65 @@ def bar(foo):
click_repl.register_repl(cli)

with pytest.raises(SystemExit):
cli()
cli(args=[], prog_name="test_simple_repl")


def test_repl_dispatches_subcommand(capsys):
@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
if ctx.invoked_subcommand is None:
click_repl.repl(ctx)

@cli.command()
def foo():
print("Foo!")

with mock_stdin("foo\n"):
with pytest.raises(SystemExit):
cli(args=[], prog_name="test_repl_dispatch_subcommand")
assert capsys.readouterr().out == "Foo!\n"


def test_group_command_called_once(capsys):
@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
print("cli()")
if ctx.invoked_subcommand is None:
click_repl.repl(ctx)

@cli.command()
def foo():
print("Foo!")

@cli.command()
def bar():
print("Bar!")

with mock_stdin("foo\nbar\n"):
with pytest.raises(SystemExit):
cli(args=[], prog_name="test_group_called_once")
assert capsys.readouterr().out == "cli()\nFoo!\nBar!\n"


def test_independant_args(capsys):
@click.group(invoke_without_command=True)
@click.argument("argument")
@click.pass_context
def cli(ctx, argument):
print("cli(%s)" % argument)
if ctx.invoked_subcommand is None:
click_repl.repl(ctx)

@cli.command()
def foo():
print("Foo!")

with mock_stdin("foo\n"):
with pytest.raises(SystemExit):
cli(args=["command-line-argument"], prog_name="test_group_called_once")
assert capsys.readouterr().out == "cli(command-line-argument)\nFoo!\n"


def test_exit_repl_function():
Expand All @@ -41,7 +114,7 @@ def repl():
click_repl.repl(click.get_current_context())

try:
cli()
cli(args=[], prog_name="test_inputs")
except (SystemExit, Exception) as e:
if (
type(e).__name__ == "prompt_toolkit.output.win32.NoConsoleScreenBufferError"
Expand Down

0 comments on commit 0960d14

Please sign in to comment.