Skip to content
Myr

test_testing.py

This file

Path

tests/test_testing.py

409 lines · 10.3 KiB · Python

Last changed by

Keep track of `<stderr>` and `<stdout>` mix in `CliRunner` results (#2523)Kevin Deldyckebefore adoption0e0c003

History of this file

Take it

1import os2import sys3from io import BytesIO45import pytest67import click8from click.testing import CliRunner91011def test_runner():12    @click.command()13    def test():14        i = click.get_binary_stream("stdin")15        o = click.get_binary_stream("stdout")16        while True:17            chunk = i.read(4096)18            if not chunk:19                break20            o.write(chunk)21            o.flush()2223    runner = CliRunner()24    result = runner.invoke(test, input="Hello World!\n")25    assert not result.exception26    assert result.output == "Hello World!\n"272829def test_echo_stdin_stream():30    @click.command()31    def test():32        i = click.get_binary_stream("stdin")33        o = click.get_binary_stream("stdout")34        while True:35            chunk = i.read(4096)36            if not chunk:37                break38            o.write(chunk)39            o.flush()4041    runner = CliRunner(echo_stdin=True)42    result = runner.invoke(test, input="Hello World!\n")43    assert not result.exception44    assert result.output == "Hello World!\nHello World!\n"454647def test_echo_stdin_prompts():48    @click.command()49    def test_python_input():50        foo = input("Foo: ")51        click.echo(f"foo={foo}")5253    runner = CliRunner(echo_stdin=True)54    result = runner.invoke(test_python_input, input="bar bar\n")55    assert not result.exception56    assert result.output == "Foo: bar bar\nfoo=bar bar\n"5758    @click.command()59    @click.option("--foo", prompt=True)60    def test_prompt(foo):61        click.echo(f"foo={foo}")6263    result = runner.invoke(test_prompt, input="bar bar\n")64    assert not result.exception65    assert result.output == "Foo: bar bar\nfoo=bar bar\n"6667    @click.command()68    @click.option("--foo", prompt=True, hide_input=True)69    def test_hidden_prompt(foo):70        click.echo(f"foo={foo}")7172    result = runner.invoke(test_hidden_prompt, input="bar bar\n")73    assert not result.exception74    assert result.output == "Foo: \nfoo=bar bar\n"7576    @click.command()77    @click.option("--foo", prompt=True)78    @click.option("--bar", prompt=True)79    def test_multiple_prompts(foo, bar):80        click.echo(f"foo={foo}, bar={bar}")8182    result = runner.invoke(test_multiple_prompts, input="one\ntwo\n")83    assert not result.exception84    assert result.output == "Foo: one\nBar: two\nfoo=one, bar=two\n"858687def test_runner_with_stream():88    @click.command()89    def test():90        i = click.get_binary_stream("stdin")91        o = click.get_binary_stream("stdout")92        while True:93            chunk = i.read(4096)94            if not chunk:95                break96            o.write(chunk)97            o.flush()9899    runner = CliRunner()100    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))101    assert not result.exception102    assert result.output == "Hello World!\n"103104    runner = CliRunner(echo_stdin=True)105    result = runner.invoke(test, input=BytesIO(b"Hello World!\n"))106    assert not result.exception107    assert result.output == "Hello World!\nHello World!\n"108109110def test_prompts():111    @click.command()112    @click.option("--foo", prompt=True)113    def test(foo):114        click.echo(f"foo={foo}")115116    runner = CliRunner()117    result = runner.invoke(test, input="wau wau\n")118    assert not result.exception119    assert result.output == "Foo: wau wau\nfoo=wau wau\n"120121    @click.command()122    @click.option("--foo", prompt=True, hide_input=True)123    def test(foo):124        click.echo(f"foo={foo}")125126    runner = CliRunner()127    result = runner.invoke(test, input="wau wau\n")128    assert not result.exception129    assert result.output == "Foo: \nfoo=wau wau\n"130131132def test_getchar():133    @click.command()134    def continue_it():135        click.echo(click.getchar())136137    runner = CliRunner()138    result = runner.invoke(continue_it, input="y")139    assert not result.exception140    assert result.output == "y\n"141142    runner = CliRunner(echo_stdin=True)143    result = runner.invoke(continue_it, input="y")144    assert not result.exception145    assert result.output == "y\n"146147    @click.command()148    def getchar_echo():149        click.echo(click.getchar(echo=True))150151    runner = CliRunner()152    result = runner.invoke(getchar_echo, input="y")153    assert not result.exception154    assert result.output == "yy\n"155156    runner = CliRunner(echo_stdin=True)157    result = runner.invoke(getchar_echo, input="y")158    assert not result.exception159    assert result.output == "yy\n"160161162def test_catch_exceptions():163    class CustomError(Exception):164        pass165166    @click.command()167    def cli():168        raise CustomError(1)169170    runner = CliRunner()171172    result = runner.invoke(cli)173    assert isinstance(result.exception, CustomError)174    assert type(result.exc_info) is tuple175    assert len(result.exc_info) == 3176177    with pytest.raises(CustomError):178        runner.invoke(cli, catch_exceptions=False)179180    CustomError = SystemExit181182    result = runner.invoke(cli)183    assert result.exit_code == 1184185186def test_with_color():187    @click.command()188    def cli():189        click.secho("hello world", fg="blue")190191    runner = CliRunner()192193    result = runner.invoke(cli)194    assert result.output == "hello world\n"195    assert not result.exception196197    result = runner.invoke(cli, color=True)198    assert result.output == f"{click.style('hello world', fg='blue')}\n"199    assert not result.exception200201202def test_with_color_but_pause_not_blocking():203    @click.command()204    def cli():205        click.pause()206207    runner = CliRunner()208    result = runner.invoke(cli, color=True)209    assert not result.exception210    assert result.output == ""211212213def test_exit_code_and_output_from_sys_exit():214    # See issue #362215    @click.command()216    def cli_string():217        click.echo("hello world")218        sys.exit("error")219220    @click.command()221    @click.pass_context222    def cli_string_ctx_exit(ctx):223        click.echo("hello world")224        ctx.exit("error")225226    @click.command()227    def cli_int():228        click.echo("hello world")229        sys.exit(1)230231    @click.command()232    @click.pass_context233    def cli_int_ctx_exit(ctx):234        click.echo("hello world")235        ctx.exit(1)236237    @click.command()238    def cli_float():239        click.echo("hello world")240        sys.exit(1.0)241242    @click.command()243    @click.pass_context244    def cli_float_ctx_exit(ctx):245        click.echo("hello world")246        ctx.exit(1.0)247248    @click.command()249    def cli_no_error():250        click.echo("hello world")251252    runner = CliRunner()253254    result = runner.invoke(cli_string)255    assert result.exit_code == 1256    assert result.output == "hello world\nerror\n"257258    result = runner.invoke(cli_string_ctx_exit)259    assert result.exit_code == 1260    assert result.output == "hello world\nerror\n"261262    result = runner.invoke(cli_int)263    assert result.exit_code == 1264    assert result.output == "hello world\n"265266    result = runner.invoke(cli_int_ctx_exit)267    assert result.exit_code == 1268    assert result.output == "hello world\n"269270    result = runner.invoke(cli_float)271    assert result.exit_code == 1272    assert result.output == "hello world\n1.0\n"273274    result = runner.invoke(cli_float_ctx_exit)275    assert result.exit_code == 1276    assert result.output == "hello world\n1.0\n"277278    result = runner.invoke(cli_no_error)279    assert result.exit_code == 0280    assert result.output == "hello world\n"281282283def test_env():284    @click.command()285    def cli_env():286        click.echo(f"ENV={os.environ['TEST_CLICK_ENV']}")287288    runner = CliRunner()289290    env_orig = dict(os.environ)291    env = dict(env_orig)292    assert "TEST_CLICK_ENV" not in env293    env["TEST_CLICK_ENV"] = "some_value"294    result = runner.invoke(cli_env, env=env)295    assert result.exit_code == 0296    assert result.output == "ENV=some_value\n"297298    assert os.environ == env_orig299300301def test_stderr():302    @click.command()303    def cli_stderr():304        click.echo("1 - stdout")305        click.echo("2 - stderr", err=True)306        click.echo("3 - stdout")307        click.echo("4 - stderr", err=True)308309    runner_mix = CliRunner()310    result_mix = runner_mix.invoke(cli_stderr)311312    assert result_mix.output == "1 - stdout\n2 - stderr\n3 - stdout\n4 - stderr\n"313    assert result_mix.stdout == "1 - stdout\n3 - stdout\n"314    assert result_mix.stderr == "2 - stderr\n4 - stderr\n"315316    @click.command()317    def cli_empty_stderr():318        click.echo("stdout")319320    runner = CliRunner()321    result = runner.invoke(cli_empty_stderr)322323    assert result.output == "stdout\n"324    assert result.stdout == "stdout\n"325    assert result.stderr == ""326327328@pytest.mark.parametrize(329    "args, expected_output",330    [331        (None, "bar\n"),332        ([], "bar\n"),333        ("", "bar\n"),334        (["--foo", "one two"], "one two\n"),335        ('--foo "one two"', "one two\n"),336    ],337)338def test_args(args, expected_output):339    @click.command()340    @click.option("--foo", default="bar")341    def cli_args(foo):342        click.echo(foo)343344    runner = CliRunner()345    result = runner.invoke(cli_args, args=args)346    assert result.exit_code == 0347    assert result.output == expected_output348349350def test_setting_prog_name_in_extra():351    @click.command()352    def cli():353        click.echo("ok")354355    runner = CliRunner()356    result = runner.invoke(cli, prog_name="foobar")357    assert not result.exception358    assert result.output == "ok\n"359360361def test_command_standalone_mode_returns_value():362    @click.command()363    def cli():364        click.echo("ok")365        return "Hello, World!"366367    runner = CliRunner()368    result = runner.invoke(cli, standalone_mode=False)369    assert result.output == "ok\n"370    assert result.return_value == "Hello, World!"371    assert result.exit_code == 0372373374def test_file_stdin_attrs(runner):375    @click.command()376    @click.argument("f", type=click.File())377    def cli(f):378        click.echo(f.name)379        click.echo(f.mode, nl=False)380381    result = runner.invoke(cli, ["-"])382    assert result.output == "<stdin>\nr"383384385def test_isolated_runner(runner):386    with runner.isolated_filesystem() as d:387        assert os.path.exists(d)388389    assert not os.path.exists(d)390391392def test_isolated_runner_custom_tempdir(runner, tmp_path):393    with runner.isolated_filesystem(temp_dir=tmp_path) as d:394        assert os.path.exists(d)395396    assert os.path.exists(d)397    os.rmdir(d)398399400def test_isolation_stderr_errors():401    """Writing to stderr should escape invalid characters instead of402    raising a UnicodeEncodeError.403    """404    runner = CliRunner()405406    with runner.isolation() as (_, err, _):407        click.echo("\udce2", err=True, nl=False)408409    assert err.getvalue() == b"\\udce2"