Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

420 lines · 10.5 KiB · Python

Last changed by

Merge pull request #1820 from saebischer/fix-clirunner-echo_stdinDavid Lordbefore adoption30e7f76

History of this file

Take it

1import os2import sys3from io import BytesIO45import pytest67import click8from click._compat import WIN9from click.testing import CliRunner101112def test_runner():13    @click.command()14    def test():15        i = click.get_binary_stream("stdin")16        o = click.get_binary_stream("stdout")17        while 1:18            chunk = i.read(4096)19            if not chunk:20                break21            o.write(chunk)22            o.flush()2324    runner = CliRunner()25    result = runner.invoke(test, input="Hello World!\n")26    assert not result.exception27    assert result.output == "Hello World!\n"282930def test_echo_stdin_stream():31    @click.command()32    def test():33        i = click.get_binary_stream("stdin")34        o = click.get_binary_stream("stdout")35        while 1:36            chunk = i.read(4096)37            if not chunk:38                break39            o.write(chunk)40            o.flush()4142    runner = CliRunner(echo_stdin=True)43    result = runner.invoke(test, input="Hello World!\n")44    assert not result.exception45    assert result.output == "Hello World!\nHello World!\n"464748def test_echo_stdin_prompts():49    @click.command()50    def test_python_input():51        foo = input("Foo: ")52        click.echo(f"foo={foo}")5354    runner = CliRunner(echo_stdin=True)55    result = runner.invoke(test_python_input, input="bar bar\n")56    assert not result.exception57    assert result.output == "Foo: bar bar\nfoo=bar bar\n"5859    @click.command()60    @click.option("--foo", prompt=True)61    def test_prompt(foo):62        click.echo(f"foo={foo}")6364    result = runner.invoke(test_prompt, input="bar bar\n")65    assert not result.exception66    assert result.output == "Foo: bar bar\nfoo=bar bar\n"6768    @click.command()69    @click.option("--foo", prompt=True, hide_input=True)70    def test_hidden_prompt(foo):71        click.echo(f"foo={foo}")7273    result = runner.invoke(test_hidden_prompt, input="bar bar\n")74    assert not result.exception75    assert result.output == "Foo: \nfoo=bar bar\n"7677    @click.command()78    @click.option("--foo", prompt=True)79    @click.option("--bar", prompt=True)80    def test_multiple_prompts(foo, bar):81        click.echo(f"foo={foo}, bar={bar}")8283    result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")84    assert not result.exception85    assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"868788def test_runner_with_stream():89    @click.command()90    def test():91        i = click.get_binary_stream("stdin")92        o = click.get_binary_stream("stdout")93        while 1:94            chunk = i.read(4096)95            if not chunk:96                break97            o.write(chunk)98            o.flush()99100    runner = CliRunner()101    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))102    assert not result.exception103    assert result.output == "Hello World!\n"104105    runner = CliRunner(echo_stdin=True)106    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))107    assert not result.exception108    assert result.output == "Hello World!\nHello World!\n"109110111def test_prompts():112    @click.command()113    @click.option("--foo", prompt=True)114    def test(foo):115        click.echo(f"foo={foo}")116117    runner = CliRunner()118    result = runner.invoke(test, input="wau wau\n")119    assert not result.exception120    assert result.output == "Foo: wau wau\nfoo=wau wau\n"121122    @click.command()123    @click.option("--foo", prompt=True, hide_input=True)124    def test(foo):125        click.echo(f"foo={foo}")126127    runner = CliRunner()128    result = runner.invoke(test, input="wau wau\n")129    assert not result.exception130    assert result.output == "Foo: \nfoo=wau wau\n"131132133def test_getchar():134    @click.command()135    def continue_it():136        click.echo(click.getchar())137138    runner = CliRunner()139    result = runner.invoke(continue_it, input="y")140    assert not result.exception141    assert result.output == "y\n"142143    runner = CliRunner(echo_stdin=True)144    result = runner.invoke(continue_it, input="y")145    assert not result.exception146    assert result.output == "y\n"147148    @click.command()149    def getchar_echo():150        click.echo(click.getchar(echo=True))151152    runner = CliRunner()153    result = runner.invoke(getchar_echo, input="y")154    assert not result.exception155    assert result.output == "yy\n"156157    runner = CliRunner(echo_stdin=True)158    result = runner.invoke(getchar_echo, input="y")159    assert not result.exception160    assert result.output == "yy\n"161162163def test_catch_exceptions():164    class CustomError(Exception):165        pass166167    @click.command()168    def cli():169        raise CustomError(1)170171    runner = CliRunner()172173    result = runner.invoke(cli)174    assert isinstance(result.exception, CustomError)175    assert type(result.exc_info) is tuple176    assert len(result.exc_info) == 3177178    with pytest.raises(CustomError):179        runner.invoke(cli, catch_exceptions=False)180181    CustomError = SystemExit182183    result = runner.invoke(cli)184    assert result.exit_code == 1185186187@pytest.mark.skipif(WIN, reason="Test does not make sense on Windows.")188def test_with_color():189    @click.command()190    def cli():191        click.secho("hello world", fg="blue")192193    runner = CliRunner()194195    result = runner.invoke(cli)196    assert result.output == "hello world\n"197    assert not result.exception198199    result = runner.invoke(cli, color=True)200    assert result.output == f"{click.style('hello world', fg='blue')}\n"201    assert not result.exception202203204def test_with_color_but_pause_not_blocking():205    @click.command()206    def cli():207        click.pause()208209    runner = CliRunner()210    result = runner.invoke(cli, color=True)211    assert not result.exception212    assert result.output == ""213214215def test_exit_code_and_output_from_sys_exit():216    # See issue #362217    @click.command()218    def cli_string():219        click.echo("hello world")220        sys.exit("error")221222    @click.command()223    @click.pass_context224    def cli_string_ctx_exit(ctx):225        click.echo("hello world")226        ctx.exit("error")227228    @click.command()229    def cli_int():230        click.echo("hello world")231        sys.exit(1)232233    @click.command()234    @click.pass_context235    def cli_int_ctx_exit(ctx):236        click.echo("hello world")237        ctx.exit(1)238239    @click.command()240    def cli_float():241        click.echo("hello world")242        sys.exit(1.0)243244    @click.command()245    @click.pass_context246    def cli_float_ctx_exit(ctx):247        click.echo("hello world")248        ctx.exit(1.0)249250    @click.command()251    def cli_no_error():252        click.echo("hello world")253254    runner = CliRunner()255256    result = runner.invoke(cli_string)257    assert result.exit_code == 1258    assert result.output == "hello world\nerror\n"259260    result = runner.invoke(cli_string_ctx_exit)261    assert result.exit_code == 1262    assert result.output == "hello world\nerror\n"263264    result = runner.invoke(cli_int)265    assert result.exit_code == 1266    assert result.output == "hello world\n"267268    result = runner.invoke(cli_int_ctx_exit)269    assert result.exit_code == 1270    assert result.output == "hello world\n"271272    result = runner.invoke(cli_float)273    assert result.exit_code == 1274    assert result.output == "hello world\n1.0\n"275276    result = runner.invoke(cli_float_ctx_exit)277    assert result.exit_code == 1278    assert result.output == "hello world\n1.0\n"279280    result = runner.invoke(cli_no_error)281    assert result.exit_code == 0282    assert result.output == "hello world\n"283284285def test_env():286    @click.command()287    def cli_env():288        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")289290    runner = CliRunner()291292    env_orig = dict(os.environ)293    env = dict(env_orig)294    assert "TEST_CLICK_ENV" not in env295    env["TEST_CLICK_ENV"] = "some_value"296    result = runner.invoke(cli_env, env=env)297    assert result.exit_code == 0298    assert result.output == "ENV=some_value\n"299300    assert os.environ == env_orig301302303def test_stderr():304    @click.command()305    def cli_stderr():306        click.echo("stdout")307        click.echo("stderr", err=True)308309    runner = CliRunner(mix_stderr=False)310311    result = runner.invoke(cli_stderr)312313    assert result.output == "stdout\n"314    assert result.stdout == "stdout\n"315    assert result.stderr == "stderr\n"316317    runner_mix = CliRunner(mix_stderr=True)318    result_mix = runner_mix.invoke(cli_stderr)319320    assert result_mix.output == "stdout\nstderr\n"321    assert result_mix.stdout == "stdout\nstderr\n"322323    with pytest.raises(ValueError):324        result_mix.stderr325326    @click.command()327    def cli_empty_stderr():328        click.echo("stdout")329330    runner = CliRunner(mix_stderr=False)331332    result = runner.invoke(cli_empty_stderr)333334    assert result.output == "stdout\n"335    assert result.stdout == "stdout\n"336    assert result.stderr == ""337338339@pytest.mark.parametrize(340    "args, expected_output",341    [342        (None, "bar\n"),343        ([], "bar\n"),344        ("", "bar\n"),345        (["--foo", "one two"], "one two\n"),346        ('--foo "one two"', "one two\n"),347    ],348)349def test_args(args, expected_output):350    @click.command()351    @click.option("--foo", default="bar")352    def cli_args(foo):353        click.echo(foo)354355    runner = CliRunner()356    result = runner.invoke(cli_args, args=args)357    assert result.exit_code == 0358    assert result.output == expected_output359360361def test_setting_prog_name_in_extra():362    @click.command()363    def cli():364        click.echo("ok")365366    runner = CliRunner()367    result = runner.invoke(cli, prog_name="foobar")368    assert not result.exception369    assert result.output == "ok\n"370371372def test_command_standalone_mode_returns_value():373    @click.command()374    def cli():375        click.echo("ok")376        return "Hello, World!"377378    runner = CliRunner()379    result = runner.invoke(cli, standalone_mode=False)380    assert result.output == "ok\n"381    assert result.return_value == "Hello, World!"382    assert result.exit_code == 0383384385def test_file_stdin_attrs(runner):386    @click.command()387    @click.argument("f", type=click.File())388    def cli(f):389        click.echo(f.name)390        click.echo(f.mode, nl=False)391392    result = runner.invoke(cli, ["-"])393    assert result.output == "<stdin>\nr"394395396def test_isolated_runner(runner):397    with runner.isolated_filesystem() as d:398        assert os.path.exists(d)399400    assert not os.path.exists(d)401402403def test_isolated_runner_custom_tempdir(runner, tmp_path):404    with runner.isolated_filesystem(temp_dir=tmp_path) as d:405        assert os.path.exists(d)406407    assert os.path.exists(d)408    os.rmdir(d)409410411def test_isolation_stderr_errors():412    """Writing to stderr should escape invalid characters instead of413    raising a UnicodeEncodeError.414    """415    runner = CliRunner(mix_stderr=False)416417    with runner.isolation() as (_, err):418        click.echo("\udce2", err=True, nl=False)419420    assert err.getvalue() == b"\\udce2"